Reputation: 379
I have a Pandas dataframe like this:
id Month
1 Month 01
1 Month 05
2 Month 12
...
And I wanted to extract the value from the Month
column and add that extraction to a new column Month_no
and obtain this output:
id Month Month_no
1 Month 01 1
1 Month 05 5
2 Month 12 12
...
Upvotes: 1
Views: 42
Reputation: 31
Alternatively:
df['Month_no'] = df['Month'].str.strip('Month').astype(int)
Upvotes: 1
Reputation: 34056
Assuming Month
column has Month and number separated by a whitespace
, you can use str.split
:
df['Month_no'] = df['Month'].str.split().str[1].astype(int)
Example:
In [1168]: df
Out[1168]:
id Month
0 1 Month 01
1 1 Month 05
2 2 Month 12
In [1169]: df['Month_no'] = df['Month'].str.split().str[1].astype(int)
In [1170]: df
Out[1170]:
id Month Month_no
0 1 Month 01 1
1 1 Month 05 5
2 2 Month 12 12
Upvotes: 1