簡體   English   中英

用上一行中的字符串替換列中的零(Python / Pandas)

[英]Replace zeros in a column with string from the row above (Python/Pandas)

我想用同一列上一行的字符串替換0。 例如:謝菲爾德(Sheffield)下的0應該讀為謝菲爾德(Sheffield)。 我正在和熊貓一起工作。

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

或者,因為看起來您已經用0代替了NaN ,所以可以省略該步驟,而只需使用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_df而不是file以不掩蓋內置的python

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM