Python 自动将字符串列转换为浮点
如何防止pandas将字符串值转换为浮点值。列Python 自动将字符串列转换为浮点,python,python-3.x,pandas,Python,Python 3.x,Pandas,如何防止pandas将字符串值转换为浮点值。列账单单据。和销售订单包含数字10-11位数字,这些数字将存储在MySQL表中的数据类型为CHAR(15)的列中。当我执行以下脚本时,我会在每个数字的末尾看到.0。我想在数据库中将它们视为字符串/字符。 Billing Doc.字段包含的数字类似于3206790137、3209056079、3209763880、3209763885、3206790137谁存储在数据库中为3206790137.0、3209056079.0、3209763880.0、32
账单单据。
和销售订单
包含数字10-11位数字,这些数字将存储在MySQL表中的数据类型为CHAR(15)的列中。当我执行以下脚本时,我会在每个数字的末尾看到.0
。我想在数据库中将它们视为字符串/字符。
Billing Doc.
字段包含的数字类似于3206790137、3209056079、3209763880、3209763885、3206790137
谁存储在数据库中为3206790137.0、3209056079.0、3209763880.0、3209763885.0、3206790137.0
。数据库中账单单据的列数据类型为CHAR(15)
当我创建一个简单的df并打印它时,问题不会出现
import pandas as pd
df = pd.DataFrame({'Sales Order': [1217252835, 1217988754, 1219068439],
'Billing Doc.': [3222102723, 3209781889, 3214305818]})
>>> df
Billing Doc. Sales Order
0 3222102723 1217252835
1 3209781889 1217988754
2 3214305818 1219068439
但是,当我阅读excel并打印它时,该列被读取为float64
file_name = "tmp/dataload/so_tracking.XLSX"
df = pd.read_excel(file_name)
print(df['Billing Doc.'])
680 3.252170e+09
681 3.252170e+09
682 3.252170e+09
683 3.252170e+09
684 3.252170e+09
685 3.252170e+09
686 3.252170e+09
687 3.252170e+09
688 3.252170e+09
689 3.252170e+09
690 3.252170e+09
.
.
.
694 3.251601e+09
695 3.251631e+09
696 3.252013e+09
697 NaN
698 3.252272e+09
699 3.252360e+09
700 3.252474e+09
.
.
Name: Billing Doc., dtype: float64
试试这个:
df = df.astype(str)
请注意,这是非常无效的
或者在将每个值插入查询之前将其转换为
int
,我自己找到了解决方案,并将其发布到这里进行记录
df = pd.read_excel(file_name, converters={'Billing Doc.' : str})
print(df['Billing Doc.'])
695 3251631331
696 3252012614
697 NaN
698 3252272451
699 3252359504
700 3252473894
701 NaN
702 NaN
703 NaN
704 3252652940
705 NaN
706 NaN
707 NaN
708 NaN
Name: Billing Doc., dtype: object
类似的情况也发生在我身上,因为新列的索引与原始数据帧的索引不匹配,这导致了NaNs,这导致自动广播浮动。因此,请检查是否:
- 原始数据帧的索引与新列匹配
- 新列包含NAN
pd.read\u csv('file.csv',dtype=object)
,它防止熊猫将数字转换为浮点数。我确信您可以用其他数据帧创建函数替换read\u csv()
。@PaulH我添加了一个示例。@pshep123。谢谢你的意见。它是一个.xlsx文件,无法转换为csv,因为我从其他地方获取它。不,我建议您使用dtype=object
作为read\u excel()
参数。我还没有测试过,但可能值得一试。
df = pd.read_excel(file_name, converters={'Billing Doc.' : str})
print(df['Billing Doc.'])
695 3251631331
696 3252012614
697 NaN
698 3252272451
699 3252359504
700 3252473894
701 NaN
702 NaN
703 NaN
704 3252652940
705 NaN
706 NaN
707 NaN
708 NaN
Name: Billing Doc., dtype: object