Home > Software design >  dataframe if string contains substring divide by 1000
dataframe if string contains substring divide by 1000

Time:08-24

I have this dataframe looking like the below dataframe.

import pandas as pd

data = [['yellow', '800test' ], ['red','900ui'], ['blue','900test'], ['indigo','700test'], ['black','400ui']]
df = pd.DataFrame(data, columns = ['Donor', 'value'])

In the value field, if a string contains say 'test', I'd like to divide these numbers by 1000. What would be the best way to do this?

CodePudding user response:

Check Below code using lambda function

df['value_2'] = df.apply(lambda x: str(int(x.value.replace('test',''))/1000) 'test' if x.value.find('test') > -1 else x.value, axis=1)
df

Output:

enter image description here

CodePudding user response:

df["value\d"] = df.value.str.findall("\d ").str[0].astype(int)
df["value\w"] = df.value.str.findall("[^\d] ").str[0]
df.loc[df["value\w"] == "test", "value\d"]  = df["value\d"]/1000
df["value"] = df["value\w"]   df["value\d"].astype(str)
  • Related