簡體   English   中英

熊貓將新列添加到具有條件的現有數據框

[英]pandas adding new column to existing dataframe with condition

我有一個像這樣的熊貓數據框。

水果 價格
蘋果 2018 4
蘋果 2019 3
蘋果 2020 5
李子 2019 3
李子 2020 2

我想添加列 [last_year_price]

請幫忙......

為此,您可以使用groupbyshift

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM