你会想做这样的事情:
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]
警告来自于我们正在更改数据框视图的值,这会影响原始数据框.然而,这就是我们希望做的事情,所以它并不关心我们.
(Python 2.7.12和Pandas 0.19.0)
编辑:
更改最后一行代码
df['ad_requests'][index]=df['ad_requests'][index-1]-df['impressions'][index-1]
至
df.at[index,'ad_requests']=df.at[index-1,'ad_requests']-df.at[index-1,'impressions']
消除了禁止任何警告的需要:
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']