【问题标题】:Load only first two columns from CSV file using Pandas使用 Pandas 仅从 CSV 文件加载前两列
【发布时间】:2021-07-23 14:38:07
【问题描述】:

我有以下格式的 df:

       0          A           84         13.0          69.0   ...  45
       1          B           76         77.0          127.0  ...  55
       2          C           28         69.0          16.0   ...  66
       3          D           28         28.0          31.0   ...  44

形状为:160,000 X 20000

我无法将整个数据帧加载到内存中。另外我只需要将前两列读入内存。应该怎么做呢?请注意,我没有任何列名可以使用 use_cols

【问题讨论】:

  • @DaSong 用了好久,还是没有加载。它是在加载整个数据框吗?
  • 您可以尝试使用标准的csv 模块并仅加载前两列
  • @AndrejKesely 如果你能在下面提供答案,我可以用打勾来验证它,以便对未来的读者有用
  • @Neo 我发布了一个例子

标签: python-3.x pandas dataframe


【解决方案1】:

试试:

import csv

data = []
with open("your_data.csv", "r") as f_in:
    csvreader = csv.reader(
        f_in
    )  # configure reader here, for example separator, quotechars

    # skip headers (if any)
    next(csvreader)

    for col1, col2, *_ in csvreader:
        data.append([col1, col2])

df = pd.DataFrame(data, columns=["col1", "col2"])
print(df)

【讨论】:

    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2017-10-21
    • 2020-07-08
    • 2020-04-10
    • 2017-11-12
    相关资源
    最近更新 更多