I need to replace every cell in a python dataframe if it contains the string p.
A B C
150 5 5p
10 4 8p
1 20 10
to make it look like
A B C
150 5 None
10 4 None
1 20 10
I tried it with
df.replace(df['C'] == df['C'].str.contains('d'), value =None)
which didnt work, can someone tell me why it didnt?
CodePudding user response:
You could use applymap
:
import pandas as pd
df = pd.DataFrame({"A":[150, 10, 1], "B":[5,4,20], "C":["5p", "8p", 10]})
df.applymap(lambda x: float(str(x).replace("p","")))
OUTPUT
A B C
0 150.0 5.0 5.0
1 10.0 4.0 8.0
2 1.0 20.0 10.0
FOLLOW UP
Following the comment by @n1colas.m, this is the approach if you want None
instead of a number parsing:
df.applymap(lambda x: None if "p" in str(x) else x)
OUTPUT
A B C
0 150 5 NaN
1 10 4 NaN
2 1 20 10.0
or
df.applymap(lambda x: "None" if "p" in str(x) else x)
OUTPUT
A B C
0 150 5 None
1 10 4 None
2 1 20 10