NoobCoder
NoobCoder

Reputation: 675

Changing the value of Pandas Dataframe Column on by checking condition of other column

My Dataframe have 2 columns one contains it unit and other having it value.

     df4 = pd.DataFrame({'D': ['g', 'Kg', 'l', 'ml'],
                         'F': ['500', '1', '1', '1000']})

I am trying to convert Kg into g and l to ml. I tried this:

    for row in final_df.iterrows():
        if final_df['D']=='Kg': 
            final_df['F']=(final_df['F']*1000)
            final_df['D']='g'
        elif final_df['D']=='l':
            final_df['F']=(final_df['F']*1000)
            final_df['D']='ml'

Expected Output:

    D   F
    g   500
    g   1000
    ml  1000
    ml  1000




    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Upvotes: 2

Views: 993

Answers (5)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With combination of to_numeric + isin + replace functions:

In [215]: df = pd.DataFrame({'D': ['g', 'Kg', 'l', 'ml'], 'F': ['500', '1', '1', '1000']}) 

In [216]: df.F = pd.to_numeric(df.F)

In [217]: df.loc[df.D.isin(['Kg','l']), 'F'] *= 1000

In [218]: df.D.replace(to_replace={'Kg': 'g', 'l': 'ml'}, inplace=True)

In [219]: df
Out[219]: 
    D     F
0   g   500
1   g  1000
2  ml  1000
3  ml  1000

Upvotes: 0

Joe
Joe

Reputation: 12417

You can use this:

df['F'] = np.where(df['D'].isin(['Kg','l']), df['F'].astype(int) * 1000, df['F'])
df['D'] = np.where(df['D']=='Kg', 'g', df['D'])
df['D'] = np.where(df['D']=='l', 'ml', df['D'])

Output:

    D     F
0   g   500
1   g  1000
2  ml  1000
3  ml  1000

Upvotes: 0

Jondiedoop
Jondiedoop

Reputation: 3353

In addition to Viveks answer using np.where, you could also consider the df.mask, which is a method specifically to update a column where a condition is true:

df4['F'] = pd.to_numeric(df4['F'])
df4['F'].mask(df4['D'].isin(['Kg', 'l']), df4['F'] * 1000, inplace=True)
#    D     F
#0   g   500
#1  Kg  1000
#2   l  1000
#3  ml  1000

Upvotes: 0

Amit Amola
Amit Amola

Reputation: 2510

So a couple of issues with this code Dheeraj. I'll try to explain them one by one.

  • The first thing that you are trying to set your numeric type values under column F as String objects by putting them inside inverted commas and trying to divide a string via an integer. So obviously it will give you an error.
  • Secondly, you're trying to put a conditional statement on the whole column by using final_df['D']=='Kg'; while you are iterating over row by row. So if you are doing this via iterations, then you should refer to a certain row as well, like this - final_df['D'][row]=='Kg'
  • Another issue is with the iteration method. While your loop was iterating 4 times, but it was of no good to iterate over using iterrows(). I'll suggest to use the length and create the range of values and use this as an index(which you can see on my answer below).
  • And the last issue is rather depending on what were you trying to do; so if you want to convert Kg and Litre to Gram and mL, then you should multiply and not divide.

Here's the code:

final_df = pd.DataFrame({'D': ['g', 'Kg', 'l', 'ml'],'F': [500, 1, 1, 1000]})

for row in range(len(list(final_df.iterrows()))):
    if final_df['D'][row]=='Kg' or final_df['D'][row]=='l':
        final_df['F'][row]=final_df['F'][row]*1000

print(final_df)

Result:

    D     F
0   g   500
1  Kg  1000
2   l  1000
3  ml  1000

Upvotes: 1

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use -

df4['F'].astype(int).where( ~((df4['D']=='Kg') | (df4['D']=='l')),  df4['F'].astype(int)*1000)

Output

0     500
1    1000
2    1000
3    1000
Name: F, dtype: int64

Upvotes: 0

Related Questions