2

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

jainam shah
  • 199
  • 1
  • 11

2 Answers2

4

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

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
anky
  • 74,114
  • 11
  • 41
  • 70