Tie_24
Tie_24

Reputation: 647

Convert value columns in dataframe

     A     B       C
0  mel  0.00    3.99
1  sid  7.23   13.30
2  alc  0.00    2.14
3  fas  8.12  108.00

I want to convert 0.00 values in their respective C column values.

The output must be:

     A     B       C
0  mel  3.99    3.99
1  sid  7.23   13.30
2  alc  2.14    2.14
3  fas  8.12  108.00

I´ve tried:

df.replace(["0.00"], ["C"])

Upvotes: 0

Views: 36

Answers (4)

YOLO
YOLO

Reputation: 21709

Another one liner:

df['D'] = df.C.combine_first(df.B)

Upvotes: 0

jpp
jpp

Reputation: 164663

One way:

df.loc[df['B'].eq(0), 'B'] = df['C']

Result:

     A     B       C
0  mel  3.99    3.99
1  sid  7.23   13.30
2  alc  2.14    2.14
3  fas  8.12  108.00

Upvotes: 0

pault
pault

Reputation: 43504

Another way:

Get the indexes of the rows you want to fill. Then replace those values:

idx = df["B"] == 0
df.loc[idx, "B"] = df.loc[idx, "C"]
print(df)
#     A     B       C
#0  mel  3.99    3.99
#1  sid  7.23   13.30
#2  alc  2.14    2.14
#3  fas  8.12  108.00

You could do this as a one-liner, but I put I wrote it like this for clarity.

Upvotes: 1

BENY
BENY

Reputation: 323226

replace+ bfill

df.replace(0,np.nan).bfill(1)
Out[2049]: 
     A     B     C
0  mel  3.99  3.99
1  sid  7.23  13.3
2  alc  2.14  2.14
3  fas  8.12   108

Or

df.loc[df.B==0,'B']=df.C
df
Out[2052]: 
     A     B       C
0  mel  3.99    3.99
1  sid  7.23   13.30
2  alc  2.14    2.14
3  fas  8.12  108.00

Upvotes: 2

Related Questions