我有一個帶有 lat long 值的資料框,其型別應該是浮點數。但是,對于某些行,您可以找到諸如 -74.128815° 之類的內容,字串末尾帶有“°”字符。
| ID | 緯度 | 長 |
|---|---|---|
| 1 | 4.807 | -75.684 |
| 2 | 4.5405 | -75.6658 |
| 3 | -74.128815° | |
| 4 | 5.35002 | -72.4002 |
| 5 | 4.6774° | -75.693 |
我想保持所有浮點值不變,但替換包含“°”的值(然后將它們轉換為浮點數),所以最后我有這個:
| ID | 緯度 | 長 |
|---|---|---|
| 1 | 4.807 | -75.684 |
| 2 | 4.5405 | -75.6658 |
| 3 | -74.128815 | |
| 4 | 5.35002 | -72.4002 |
| 5 | 4.6774 | -75.693 |
DataFrame 被命名為 df。我試過
df[df['Lat'].str.contains('°')]
哪個加注ValueError: Cannot mask with non-boolean array containing NA / NaN values error
另外,我也試過df['Lat'] = np.where(df['Lat'].str.contains('°'), df['Lat'][:-1], df['Lat'])哪個加注ValueError: operands could not be broadcast together
uj5u.com熱心網友回復:
您可以replace使用空字串將無效字符,然后使用pd.to_numeric:
degree_sign = u'\N{DEGREE SIGN}' # or degree_sign = "°"
df[['lat', 'long']].replace(degree_sign, '', regex=True)\
.apply(pd.to_numeric, errors='coerce')
uj5u.com熱心網友回復:
使用regex替換列中的最后一個非數字字符 ('\D '),然后轉換為浮點數:
df[['Lat', 'Long']].replace('\\D $', '', regex = True).astype(float)
Lat Long
0 4.80700 -75.684000
1 4.54050 -75.665800
2 NaN -74.128815
3 5.35002 -72.400200
4 4.67740 -75.693000
uj5u.com熱心網友回復:
您可以進行字串替換,然后更改列型別,例如
df['Lat'] = df['Lat'].astype('str').str.replace('°', '', regex=True).astype('float')
df['Long'] = df['Long'].astype('str').str.replace('°', '', regex=True).astype('float')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488823.html
上一篇:有沒有辦法將串列轉換為字串?
