如何将 .txt 文件作为整数而不是字符串导入 DataFrame?

How to import .txt file to DataFrame as integers, not as string?

我有 file.txt:

1,2,3,4;5,6
7,8,2,1;
2,9;1

我需要将此数据导入到 DataFrame 中以“;”分隔的列中,所以我这样做:

import pandas as pd
data = pd.read_csv('file.txt', sep = ';', names = ['Col1', 'Col2'])
data = data.fillna('0')

结果我得到:

Col1       Col2
1,2,3,4    5,6
7,8,2,1    0
2,9        1

这些行采用字符串格式。但是我需要每一行中的整数或整数列表,例如:

Col1       Col2
[1,2,3,4]  [5,6]
[7,8,2,1]  [0]
[2,9]      [1]

或者只是数字,不是字符串,也不是列表。怎么做?

您可以使用 pandas.read_csvdtypeconverters 关键字:

dtype=int
converters={'Col1': int, 'Col2': int}

要获取每个单元格中的整数列表,您可以使用如下内容:

for col in data.columns:
    data[col] = data[col].apply(lambda x: [int(y) for y in x.split(',')])

data.head()

    Col1            Col2
 0  [1, 2, 3, 4]    [5, 6]
 1  [7, 8, 2, 1]    [0]
 2  [2, 9]          [1]