Reputation: 675
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
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
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
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
Reputation: 2510
So a couple of issues with this code Dheeraj. I'll try to explain them one by one.
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
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