price
price date fruit
0 0.83 2010-01-04 banana
1 0.05 2010-01-04 appple
如何使用forloop修改列表中的项目?我的目的是:
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
我尝试过
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
答案 0 :(得分:1)
我认为您可以做到:
# 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