arv
arv

Reputation: 398

How to use a for loop to append items in a list?

price
    price      date        fruit
0   0.83    2010-01-04      banana
1   0.05    2010-01-04      appple

How can you use a forloop to ammend items in a list? My aim is to do:

price = price.set_index('date').dropna(how='all').resample('W').last()```
keep if fruit == banana
drop the column fruit
perform calculations
repeat for all other fruits in the dataset price

I tried

fruits = ['apple', 'banana', 'pair']
listxx = [(price, "price")]
for fruit in fruits:
    for i, (x, y) in enumerate(listxx):
        listxx[i] = x['fruit'] == fruit
        listxx[i] = x.set_index('date').dropna(how='all').resample('W').last()
        listxx[i].drop(listxx[i].columns[fruit], axis=1, inplace=True)
        perform calculations

Upvotes: 0

Views: 89

Answers (1)

YOLO
YOLO

Reputation: 21709

I think you can do:

# convert to datetime and set index
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')

# do calculations
df = (df
     .groupby('fruit', as_index=False)
     .resample('W')
     .last()
     .drop("fruit", axis=1))

print(df)
             
  date         price    
0 2010-01-10   0.05
1 2010-01-10   0.83

Upvotes: 1

Related Questions