在 Pandas DataFrame 中抓取前一年的数据

我有这个 df:


d={'year':[2019,2018,2017],'B':[10,5,17]}

df=pd.DataFrame(data=d)


print(df):


   year   B

0  2019  10

1  2018   5

2  2017  17

我想创建一个列“B_previous_year”,从前一年获取 B 数据,其方式如下所示:


   year   B   B_previous_year

0  2019  10                 5

1  2018   5                17

2  2017  17               NaN

我正在尝试这个:


df['B_previous_year']=df.B.loc[df.year == (df.year - 1)]

然而我B_previous_year已经满了NaN


   year   B  B_previous_year

0  2019  10              NaN

1  2018   5              NaN

2  2017  17              NaN

我怎么能那样做?


ABOUTYOU
浏览 149回答 2
2回答

猛跑小猪

如果您想保留整数格式:df = df.convert_dtypes()df['New'] = df.B.shift(-1)df输出:&nbsp; &nbsp; year&nbsp; &nbsp; B&nbsp; &nbsp;New0&nbsp; &nbsp;2019&nbsp; &nbsp; 10&nbsp; 51&nbsp; &nbsp;2018&nbsp; &nbsp; 5&nbsp; &nbsp;172&nbsp; &nbsp;2017&nbsp; &nbsp; 17&nbsp; <NA>

蝴蝶不菲

您可能想先按年份对数据框进行排序,然后验证一行与下一行的差异确实是一年:df = df.sort_values(by='year')df['B_previous_year'] = df[df.year.diff() == 1]['B']&nbsp; &nbsp; year&nbsp; &nbsp; B&nbsp; &nbsp;B_previous_year2&nbsp; &nbsp;2017&nbsp; &nbsp; 17&nbsp; NaN&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp;2018&nbsp; &nbsp; 5&nbsp; &nbsp;5.0&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp;2019&nbsp; &nbsp; 10&nbsp; 10.0&nbsp; &nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python