简体   繁体   English

熊猫将新列添加到具有条件的现有数据框

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

I have a pandas data frame like so.我有一个像这样的熊猫数据框。

fruit水果 year price价格
apple苹果 2018 2018 4 4
apple苹果 2019 2019 3 3
apple苹果 2020 2020 5 5
plum李子 2019 2019 3 3
plum李子 2020 2020 2 2

and I want to add column [last_year_price]我想添加列 [last_year_price]

please help......请帮忙......

为此,您可以使用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)

Use DataFrameGroupBy.idxmax for rows with maximal years and join to oriinal DataFrame:对具有最长年份的行使用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