简体   繁体   中英

How do I remove certain parts of cells in a column using Python?

So I have a column of strings of numbers in which certain cells have words ahead of the strings. It looks a little something like this:

Names Values
First '9.90'
Second '9.68'
Third '9.45'
Fourth 'Loan fee:8.10'
Fifth '9.98'

Now I've tried a lot of different ideas just to get the 'Loan fee:' removed, basically i first converted it into a list called newz and then tried

e=[]
for i in newz:
    i.replace('Loan fee:','')
    e.append(i)

Tried using regex as well:

def change(i):
    re.sub('Loan fee:','',i)

result = list(map(lambda x: change(x),newz))

So far nothing's worked

If you're using Pandas:

import pandas as pd

df = pd.DataFrame({
    'Names': ['First', 'Second', 'Third', 'Fourth', 'Fifth'],
    'Values': ['9.90', '9.68', '9.45', 'Loan fee:8.10', '9.98']
})

df['Values'] = df['Values'].str.replace('Loan fee:', '')
print(df)

Outputs

    Names Values
0   First   9.90
1  Second   9.68
2   Third   9.45
3  Fourth   8.10
4   Fifth   9.98

str.replace returns a new string. Also you should first check whether the string contains 'Loan fee:' and then replace it.

So you should do:

e=[]
for i in newz:
    if "Loan fee:" in i:
        s = i.replace('Loan fee:','')
        e.append(s)
    else:
        e.append(i)

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