Using the values of a previous “row” in a pandas series

人走茶凉 提交于 2019-12-05 11:01:24

You'll want to do something like this:

pd.options.mode.chained_assignment = None #suppresses "SettingWithCopyWarning"
for index, elem in enumerate(df['ad_requests']):
    if pd.isnull(elem):
        df['ad_requests'][index]=df['ad_requests'][index-1]-df['impressions'][index-1]

The warning comes from the fact that we're changing the values of a view of a dataframe, which affects the original dataframe. That is what we wish to do, however, so it doesn't really concern us.

(Python 2.7.12 and Pandas 0.19.0)

EDIT:

Changing the last line of code from

df['ad_requests'][index]=df['ad_requests'][index-1]-df['impressions'][index-1]

to

df.at[index,'ad_requests']=df.at[index-1,'ad_requests']-df.at[index-1,'impressions']

removes the need to suppress any warnings:

for index, elem in enumerate(df['ad_requests']):
    if pd.isnull(elem):
        df.at[index,'ad_requests']=df.at[index-1,'ad_requests']-df.at[index-1,'impressions']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!