首页 > 解决方案 > 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')

恢复:

标签: pandastype-conversion

解决方案


该数字是 32 位的下限。您的号码超出了您尝试使用的 int32 范围,因此它会返回限制(注意 2**32 = 4294967296 除以 2 2147483648 即您的号码)。

您应该改用 astype(int64) 。


推荐阅读