Home > database >  Replace value from previous row in same column
Replace value from previous row in same column

Time:08-24

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?

CodePudding user response:

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

CodePudding user response:

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)
  • Related