无法剥离列中的字符串值,然后将其转换为 Python 中的整数
Trouble stripping down string values within a column, then converting it to an integer in Python
问候 Stack Overflow 社区!
我正在尝试执行一个看似简单的操作,但结果却让我非常沮丧!
请允许我简单解释一下:我有这个数据框...
print(dfx)
Select a BW Speed
0 50 Mb
1 100 Mb
2 100 Mb
3 50 Mb
4 50 Mb
我需要一段代码,通过 1) 去除 space 和 "Mb" 字符,然后 2) 将其转换为 Int(或浮点数) , even) 这样我就可以进一步执行 comparisons/analysis 了。我基本上只想要数据的数字部分,没有别的!
这是理想情况下的示例:
print(dfx)
Select a BW Speed
0 50
1 100
2 100
3 50
4 50
这是我最近的尝试:
dfx ['Select a BW Speed']= dfx['Select a BW Speed'].str.replace(r'\D', '').astype(int)
导致此错误....
ValueError: cannot convert float NaN to integer
我在这里做错了什么?非常感谢任何帮助:)
最佳,
-克里斯托弗
问题出在尝试转换为 int
NaN
值。因此,您需要 pd.to_numeric
来处理这些情况。下面是使用 panda 的 str
访问器方法的方法:
pd.to_numeric(df['Select a BW Speed'].str.split().str[0], errors='coerce')
0 50
1 100
2 100
3 50
4 50
Name: Select a BW Speed, dtype: int64
或使用您自己的方法:
pd.to_numeric(df['Select a BW Speed'].str.replace(r'\D', ''), errors='coerce')
问候 Stack Overflow 社区!
我正在尝试执行一个看似简单的操作,但结果却让我非常沮丧!
请允许我简单解释一下:我有这个数据框...
print(dfx)
Select a BW Speed
0 50 Mb
1 100 Mb
2 100 Mb
3 50 Mb
4 50 Mb
我需要一段代码,通过 1) 去除 space 和 "Mb" 字符,然后 2) 将其转换为 Int(或浮点数) , even) 这样我就可以进一步执行 comparisons/analysis 了。我基本上只想要数据的数字部分,没有别的!
这是理想情况下的示例:
print(dfx)
Select a BW Speed
0 50
1 100
2 100
3 50
4 50
这是我最近的尝试:
dfx ['Select a BW Speed']= dfx['Select a BW Speed'].str.replace(r'\D', '').astype(int)
导致此错误....
ValueError: cannot convert float NaN to integer
我在这里做错了什么?非常感谢任何帮助:)
最佳,
-克里斯托弗
问题出在尝试转换为 int
NaN
值。因此,您需要 pd.to_numeric
来处理这些情况。下面是使用 panda 的 str
访问器方法的方法:
pd.to_numeric(df['Select a BW Speed'].str.split().str[0], errors='coerce')
0 50
1 100
2 100
3 50
4 50
Name: Select a BW Speed, dtype: int64
或使用您自己的方法:
pd.to_numeric(df['Select a BW Speed'].str.replace(r'\D', ''), errors='coerce')