Search code examples
pythonpython-3.xpandasdataframenumber-formatting

Adding value 0 to existing column based on comma


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?


Solution

  • 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