I have a dataframe like this:
|number |
1 |122 |
2 |345 |
3 | 456|
4 | 789|
I want to change it into:
|number|
1 |nan|
2 |nan|
3 |456|
4 |789|
i want only right align value
I have a dataframe like this:
|number |
1 |122 |
2 |345 |
3 | 456|
4 | 789|
I want to change it into:
|number|
1 |nan|
2 |nan|
3 |456|
4 |789|
i want only right align value
I think you need test Series.str.endswith
if space, then replace to NaN
by Series.mask
, remove possible traling spaces by Series.str.strip
and convert to floats:
df['number'] = df['number'].mask(df['number'].str.endswith(' ')).str.strip().astype(float)
Or:
df['number'] = df['number'].mask(df['number'].str[-1] == ' ').str.strip().astype(float)
print (df)
number
1 NaN
2 NaN
3 456.0
4 789.0
If want integers it is possible by integer na working in pandas 0.24+:
m = df['number'].str.endswith(' ')
df['number'] = df['number'].mask(m).str.strip().astype(float).astype('Int64')
print (df)
number
1 NaN
2 NaN
3 456
4 789
you can use series.str.split()
to split the strings and grab the end element from the split and convert to numeric using pd.to_numeric
:
df['number']=pd.to_numeric(df['number'].str.split(' ').str[-1],errors='coerce')
Tested on:
s=pd.Series(['122 ','345 ',' 456',' 789'])
pd.to_numeric(s.str.split(' ').str[-1],errors='coerce')
0 NaN
1 NaN
2 456.0
3 789.0
dtype: float64