简体   繁体   中英

Replace value from previous row in same column

I have a column in dataframe like this

test_data = pd.DataFrame({'Category':['Finance - Loan','1','2','3','4','Finance - Loan - Car','1','2', 'Car - Loan','1', '2', '3']})

How do i replace the number with the value before. The data type is string. Is there anyone can help?

You can replace the numeric strings with NaN and use fillna() method

col = df['Category']
col[col.str.isnumeric()] = None
col = col.fillna(method='ffill')
df['Category'] = col

Result

    Category
0   Finance - Loan
1   Finance - Loan
2   Finance - Loan
3   Finance - Loan
4   Finance - Loan
5   Finance - Loan - Car
6   Finance - Loan - Car
7   Finance - Loan - Car
8   Car - Loan
9   Car - Loan
10  Car - Loan
11  Car - Loan

Edit: bui answer is better.

import pandas as pd

test_data = pd.DataFrame(
{'Category': ['Finance - Loan', '1', '2', '3', '4', 'Finance - Loan - Car', '1', '2', 'Car - Loan', '1', '2', '3']})
lst = test_data['Category'].tolist()
test = []
for i in lst:
    if not i.isdigit():
        test.append(i)
    if i.isdigit():
        test.append(test[-1])
test_data['Category'] = test
print(test_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM