Заменить нули в столбце на строку из строки выше (Python / Pandas)

1

Я бы хотел заменить 0 на строку из того же столбца, предыдущей строки. Например: 0 под Шеффилдом должен прочитать Шеффилд. Я работаю с пандами.

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
Теги:
pandas

1 ответ

2

Используйте 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 file_df вместо file чтобы не замаскировать встроенный python

Ещё вопросы

Сообщество Overcoder
Наверх
Меню