Reputation: 403
I have a DataFrame that looks like below:
name price
x ,12
y ,9
z 10,25
I have to add "0" before the comma (unless there is already a number before the comma, in that case it can't be changed) so DataFrame should looks like below:
name price
x 0,12
y 0,9
z 10,25
Do you have any ideas?
Upvotes: 0
Views: 42
Reputation: 11502
EDIT Here is a potential solution:
A B
0 1 ,2
1 2 ,02
2 3 1,3
3 4 ,9
4 5 13
5 6 12
and
df['B'] = df['B'].str.replace(",", "0,", regex=True)
df['B'] = df['B'].apply(lambda x: '{0:0>4}'.format(x))
df['B'] = df['B'].apply(lambda x: x.replace(',','.'))
df['B'] = df['B'].astype(float)
which gives
A B
0 1 0.20
1 2 0.02
2 3 1.30
3 4 0.90
4 5 13.00
5 6 12.00
Upvotes: 1
Reputation: 658
Assuming you are working with strings and not numbers, this does the trick for me:
df["price"] = df["price"].where(~df["price"].str.startswith(","), "0"+df["price"])
Here is an example
df = pd.DataFrame([["x",",12"],["y",",3"],["z","5"],["o","1,2"]], columns=["name","price"])
print("input:", df)
df["price"] = df["price"].where(~df["price"].str.startswith(","), "0"+df["price"])
print("output:", df)
yields:
input: name price
0 x ,12
1 y ,3
2 z 5
3 o 1,2
output: name price
0 x 0,12
1 y 0,3
2 z 5
3 o 1,2
Upvotes: 3