Issue
I have a pandas dataframe in python that looks like this (my actual dataframe is MUCH bigger than this):
col_1 col_2
0 0.8 0.1
1 nope 0.6
2 0.4 0.7
3 nope nope
How can I perform some operations on the numerical values of specific columns. For example, multiply the numerical values of col_2 by 10 to get something like this:
col_1 col_2
0 0.8 1
1 nope 6
2 0.4 7
3 nope nope
Although it looks like a simple task I couldn't find a solution for it anywhere on internet.
Thanks in advance.
Solution
First you need to convert the object
type columns to numeric
columns by using pd.to_numeric
:
In [141]: df.col_2 = pd.to_numeric(df.col_2, errors='coerce')
errors='coerce'
converts all non-numeric type values in the column to NaN
.
Then, multiply by 10:
In [144]: df.col_2 = df.col_2 * 10
In [145]: df
Out[145]:
col_1 col_2
0 0.8 1.0
1 nope 6.0
2 0.4 7.0
3 nope NaN
if you want to convert NaN
back to nope
, you can use df.fillna
:
In [177]: df.fillna('nope', inplace=True)
In [178]: df
Out[178]:
col_1 col_2
0 0.8 1
1 nope 6
2 0.4 7
3 nope nope
Answered By - Mayank Porwal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.