pandas - Pandas, astype(int) 应用于浮点列返回负数
问题描述
我的任务是将数据从 excel 读取到数据框。数据有点混乱,我已经完成了清理工作:
df_1 = pd.read_excel(offers[0])
df_1 = df_1.rename(columns={'Наименование [Дата Файла: 29.05.2019 время: 10:29:42 ]':'good_name',
'Штрихкод':'barcode',
'Цена шт. руб.':'price',
'Остаток': 'balance'
})
df_1 = df_1[new_columns]
# I don't know why but without replacing NaN with another char code doesn't work
df_1.barcode = df_1.barcode.fillna('_')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to numeric
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer').fillna(0)
df_1.head()
它返回 float64 类型的列条形码(为什么会这样?)
0 0.000000e+00
1 7.613037e+12
2 7.613037e+12
3 7.613034e+12
4 7.613035e+12
Name: barcode, dtype: float64
然后我尝试将该列转换为整数。
df_1.barcode = df_1.barcode.astype(int)
但我不断收到愚蠢的负数。
df_1.barcode[0:5]
0 0
1 -2147483648
2 -2147483648
3 -2147483648
4 -2147483648
Name: barcode, dtype: int32
感谢@Will 和@micric,我终于找到了解决方案。
df_1 = pd.read_excel(offers[0])
df_1 = df_1[new_columns]
# replacing NaN with 0, it'll help to convert the column explicitly to dtype integer
df_1.barcode = df_1.barcode.fillna('0')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to integer
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer')
恢复:
- pd.to_numeric 将 NaN 转换为 float64。作为具有 NaN 和非 Nan 值的列的结果,我们应该期望列 dtype float64。
- 检查您正在处理的数字的大小。int32 有其限制,即 2**32 = 4294967296。非常感谢您的帮助,伙计们!
解决方案
该数字是 32 位的下限。您的号码超出了您尝试使用的 int32 范围,因此它会返回限制(注意 2**32 = 4294967296 除以 2 2147483648 即您的号码)。
您应该改用 astype(int64) 。
推荐阅读
- python - Python `schedule` 计划任务的返回值去哪了?
- java - How to get data from OnSuccessListener
() - html - 以自己的形式搜索 Google 地址栏
- orientdb - Gremlin: Group by multiple properties from two different vertices
- python - Python modules in visual studio code
- laravel - 使用订阅时,laravel-graphql-playground 无法连接到 UI 中的 websocket
- c# - 更新 v76 后,我得到脚本在 selenium 中返回意外结果错误
- java - Create new List
() by getting member of List - >() without linking them
- mysql - 使用 concat 按周分组 SQL
- azure-devops - Azure 开发运维。复制文件。发布工件。构建成功时找到 0 个文件