我有一个大型文本文件,其中的列采用以下形式:
1255 32627 some random stuff which might have numbers 1245
1.我想使用read_csv
给我一个包含三列的数据框。前两列应为 dtype uint32,第三列仅包含字符串中的所有内容。也就是说,上面的行应该分为 1255
、32627
和 一些可能有数字 1245 的随机内容
。例如,这不会执行此操作,但至少显示了数据类型:
pd.read_csv("foo.txt", sep=' ', header=None, dtype={0:np.uint32, 1:np.uint32, 2:np.str})
2.我的第二个问题是关于 str
dtype。它使用了多少 RAM,如果我知道字符串的最大长度,我可以减少它吗?
最佳答案
您需要使用
pd.read_csv()
有什么原因吗?下面的代码很简单,可以轻松地根据您的要求修改列值。from numpy import uint32 from csv import reader from pandas import DataFrame file = 'path/to/file.csv' with open(file, 'r') as f: r = reader(f) for row in r: column_1 = uint32(row[0]) column_2 = uint32(row[1]) column_3 = ' '.join([str(col) for col in row[2::]]) data = [column_1, column_2, column_3] frame = DataFrame(data)
我不明白这个问题。您希望您的琴弦非常长吗? 32 位 Python 安装的字符串长度限制为 2-3GB。 64 位安装要大得多,仅受您可以装入系统的 RAM 量的限制。
关于python - 关于 read_csv 和 str dtype 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775494/