Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can you help me .. please
#1
Photo 
hi , in the file exel there is :

name city item spent
PIPPO uk apple 2
PIPPO uk banana 3
PIPPO uk pear 5
PIPPO uk pineapple 4
PLUTO us pasta 10
DONALD ca bread 3
DONALD ca fish 8

i wait this result :
PIPPO
LEAVE IN uk
HE BOUGHT APPLE FOR 2
HE BOUGHT BANANA FOR 3
HE BOUGHT PEAR FOR 5
HE BOUGHT PINEAPPLE FOR 4
TOT SPENT 14

PLUTO
LEAVE IN us
HE BOUGHT pasta FOR 10
TOT SPENT 10

DONALD
LEAVE IN CA
HE BOUGHT BREAD FOR 3
HE BOUGHT FISH FOR 8
TOT SPENT 11


import pandas as pd

disney = pd.read_excel('exercise.xlsx', "Sheet1" ,header=0 , )

name1 = disney["name"]
city1 = disney["city"]
item1 = disney["item"]
spent1 =disney["spent"]

name2 = name1.drop_duplicates()
city2 = city1.drop_duplicates()
for x in name2:
    
        def work():
            print(x)
            for name2 in city2:
                print("LEAVE IN "+name2)
            print("BOUGHT")
            print("TOT SPENT")
            
        work()
Output:
PIPPO LEAVE IN uk LEAVE IN us LEAVE IN ca BOUGHT TOT SPENT PLUTO LEAVE IN uk LEAVE IN us LEAVE IN ca BOUGHT TOT SPENT DONALD LEAVE IN uk LEAVE IN us LEAVE IN ca BOUGHT TOT SPENT

Attached Files

Thumbnail(s)
   
Reply
#2
Please post code and your CSV file as text, not screen shots. Posting text makes it easier for others to test solutions.

What should you do if PIPPO buys stuff in uk and us? Something like this?
Output:
PIPPO LEAVE IN uk HE BOUGHT APPLE FOR 2 HE BOUGHT PEAR FOR 5 TOT SPENT 7 LEAVE IN us HE BOUGHT BANANA FOR 3 HE BOUGHT PINAPPLE FOR 4 TOT SPENT 7
This is a fairly simple program. Don't make it harder than it needs to be. A lot of the solution comes down to organizing the data. I would sort the data by user, then city. I know your example is sorted this way, but can we assume that to always be so?

Once the rows are sorted, loop through the rows and look for things to change..

If the name changes you need to write the total for the previous person/city (if it exists), write the user name and start a new total. (i.e. TOT SPENT 14 PLUTO)
If the city changes you need to write the total for the previous city (if it exists), write a new city name, and start a new total. (does not happen in your example data)
If neither of the above is true, write the "HE BOUGHT" message and update the total.
When you run out of rows, write the current total.

Another way to solve this problem is to use grouping in Pandas, but that is more complicated than looping through the sorted rows.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020