[英]pandas adding new column to existing dataframe with condition
我有一個像這樣的熊貓數據框。
水果 | 年 | 價格 |
---|---|---|
蘋果 | 2018 | 4 |
蘋果 | 2019 | 3 |
蘋果 | 2020 | 5 |
李子 | 2019 | 3 |
李子 | 2020 | 2 |
我想添加列 [last_year_price]
請幫忙......
為此,您可以使用groupby
和shift
:
df['last_year_price'] = df.groupby('fruit').shift(1).price
您可以使用移位功能:
df['last_year_price'] = df.sort_values(by=['year'], ascending=True).groupby(['fruit'])['price'].shift(1)
對具有最長年份的行使用DataFrameGroupBy.idxmax
並加入原始 DataFrame:
df = df.merge(df.loc[df.groupby('fruit')['year'].idxmax(), ['fruit','price']].rename(columns={'price':'last_year_price'}), on='fruit', how='left')
print (df)
fruit year price last_year_price
0 apple 2018 4 5
1 apple 2019 3 5
2 apple 2020 5 5
3 plum 2019 3 2
4 plum 2020 2 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.