python - long() 的 pandas 无效文字,基数为 10 错误

标签 python pandas dataframe casting int

我正在尝试这样做:df['Num_Detections'] = df['Num_Detections'].astype(int)

我得到以下错误:

ValueError: invalid literal for long() with base 10: '12.0'

我的数据看起来如下:

>>> df['Num_Detections'].head()
Out[6]: 
sku_name
DOBRIY MORS GRAPE-CRANBERRY-RASBERRY 1L     12.0
AQUAMINERALE 5.0L                            9.0
DOBRIY PINEAPPLE 1.5L                        2.0
FRUKT.SAD APPLE 0.95L                      154.0
DOBRIY PEACH-APPLE 0.33L                    71.0
Name: Num_Detections, dtype: object

知道如何正确进行转换吗?

感谢您的帮助。

最佳答案

有一些值,不能转换为int

您可以使用 to_numeric并获取有问题的 NaN 值:

df['Num_Detections'] = pd.to_numeric(df['Num_Detections'], errors='coerce')

如果需要检查具有问题值的行,请使用 boolean indexing带面具 isnull :

print (df[ pd.to_numeric(df['Num_Detections'], errors='coerce').isnull()])

示例:

df = pd.DataFrame({'Num_Detections':[1,2,'a1']})

print (df)
  Num_Detections
0              1
1              2
2             a1

print (df[ pd.to_numeric(df['Num_Detections'], errors='coerce').isnull()])
  Num_Detections
2             a1

df['Num_Detections'] = pd.to_numeric(df['Num_Detections'], errors='coerce')
print (df)
   Num_Detections
0             1.0
1             2.0
2             NaN

关于python - long() 的 pandas 无效文字,基数为 10 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38918653/

相关文章:

Python 具有相同装饰器的多个函数在 main 中执行

python - Google App Engine + Python 中的 REST API?

python - 根据值列 pandas 计算名称

python - 数据框与缺失数据合并

python - 在 pandas to_csv 方法中保留列顺序

python - 在Python中,如何分割字符串并保留分隔符?

python - 沙发底座太大,无法存放

pandas - 根据 Pandas 中的公共(public)列值合并两个数据框

python - 按列比较 2 个 pandas 数据帧的行并保持更大和总和

python - 如何使用 id 连接数据帧行中的字符串?