【发布时间】:2020-01-28 04:36:10
【问题描述】:
在将数据框转为列表时如何防止整数转为浮点数?
我有一个包含 5 列数据的 .csv 文件。前四列没有小数点,而最后一列有。
当我使用“pd.read_csv”将此数据导入我的脚本时,数据会正确导入,前 4 个数字为整数,最后一个数字为浮点数,如下所示:
1,1,10,0,1.0
1,1,11,0,0.6
1,1,12,0,0.0
但是我需要将此数据转换为列表,并且当我这样做时,它将所有数字转换为浮点数。我不想要这个。前四个值必须是整数。
这是我当前的代码,在将其转换为列表后,它提供了一个所有数字都是浮点数的列表:
data_file_name = r'C:\Users\username\Desktop\FileName.csv'
data = pd.read_csv(data_file_name) #<This part works and the data types are correct, the first 4 are integers
data2 = data.values.tolist() #<here is where everything gets converted to a float, even if it was defined as an int in the df.
这会生成一个列表,其中的数据格式如下:
[[1.0, 1.0, 10.0, 0.0, 1.0], [1.0, 1.0, 11.0, 0.0, 0.6], [1.0, 1.0, 12.0, 0.0, 0.0]]
当我需要这样格式化时:
[[1, 1, 10, 0, 1.0], [1, 1, 11, 0, 0.6], [1, 1, 12, 0, 0.0]]
我能做什么?
我试过了:
[int(i,10) for i in data]
但这会返回此错误:
ValueError: invalid literal for int() with base 10: 'Month'
【问题讨论】:
-
查看
pd.read_csv中的dtype参数 -
@Prune 这个重复对
read_csv有什么帮助? -
转换逻辑是关键部分。
-
我在一个新的步骤中添加了我遗漏的内容 - csv 读取工作正常并且那里的数据类型正确,但即使对于定义为整数的列,也会将小数添加到列表中在df中。
-
我在这里找到了我的问题的答案,而这个问题也正是我想问的问题:stackoverflow.com/questions/34838378/…
标签: python pandas list csv integer