[英]Replace zeros in a column with string from the row above (Python/Pandas)
I would like to replace the 0 with the string from the same column, previous row. 我想用同一列上一行的字符串替换0。 Eg: 0 under Sheffield should read Sheffield. 例如:谢菲尔德(Sheffield)下的0应该读为谢菲尔德(Sheffield)。 I am working with pandas. 我正在和熊猫一起工作。
file = file[['Branch', 'Type' ,'total']]
#replace NaN with 0
file.fillna(0).tail(6)
Out[48]:
Branch Type total
394 Sheffield Sum of Resend to Branch 0
395 0 Number of PV Enquiries 83
396 Wakefield Sum of Resend to Branch 0
397 0 Number of PV Enquiries 38
398 York Sum of Resend to Branch 1
399 0 Number of PV Enquiries 59
I have tried:
a) #create a series for that column and replace
branch = file.iloc[ :, 0]
branch.replace(0, branch(-1))
# why is this series not callable?
b)# I tried a loop in the dataframe
for item in file:
if "Branch" == 0:
replace(0, "Branch"[-1])
# I am unsure how to refer to the row above
Use replace
with the method ffill
使用replace
方法ffill
file_df['Branch'].replace(to_replace='0', method='ffill', inplace=True)
>>> file_df
Branch Type total
394 Sheffield Sum of Resend to Branch 0
395 Sheffield Number of PV Enquiries 83
396 Wakefield Sum of Resend to Branch 0
397 Wakefield Number of PV Enquiries 38
398 York Sum of Resend to Branch 1
399 York Number of PV Enquiries 59
Or, since it looks like you already replaced the NaN
with 0
, you could omit that step and just use ffill
. 或者,因为看起来您已经用0
代替了NaN
,所以可以省略该步骤,而只需使用ffill
。 ie if your original dataframe looks like: 即,如果您的原始数据框看起来像:
>>> file_df
Branch Type total
394 Sheffield Sum of Resend to Branch 0
395 NaN Number of PV Enquiries 83
396 Wakefield Sum of Resend to Branch 0
397 NaN Number of PV Enquiries 38
398 York Sum of Resend to Branch 1
399 NaN Number of PV Enquiries 59
use: 采用:
file_df['Branch'].ffill(inplace=True)
Note that I called your dataframe file_df
rather than file
to not mask the python
builtin 请注意,我将您的数据file_df
称为file_df
而不是file
以不掩盖内置的python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.