gpt4 book ai didi

python - 将列中的零替换为上一行中的字符串(Python/Pandas)

转载 作者:行者123 更新时间:2023-12-01 01:44:45 25 4
gpt4 key购买 nike

我想用上一行同一列中的字符串替换 0。例如:Sheffield 下的 0 应为 Sheffield。我正在与 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

最佳答案

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

或者,由于您似乎已经将 NaN 替换为 0,因此您可以省略该步骤并仅使用 ffill如果您的原始数据框如下所示:

>>> 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

用途:

file_df['Branch'].ffill(inplace=True)

请注意,我将您的数据框称为 file_df 而不是 file ,以免屏蔽 python 内置

关于python - 将列中的零替换为上一行中的字符串(Python/Pandas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51504274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com