【问题标题】:How to create a pandas dataframe from CSV without delimiter (in python)如何从没有分隔符的CSV创建熊猫数据框(在python中)
【发布时间】:2017-06-17 12:50:14
【问题描述】:

我想从一个包含不同列但没有分隔符的 csv 文件创建一个数据框。似乎列条目之间的空格数量不同。

此外,csv 顶部的一些标题行包含自述文件信息,根本没有任何列。

我在使用 pd.read_csv() 时遇到问题

谢谢!

文件看起来像这样:

This is a header of the textfile.The header has no columns.
This is a header of the textfile.The header has no columns.
This is a header of the textfile.The header has no columns.

...
P-X1-6030-07-A01    368963
P-X1-6030-08-A01    368964
P-X1-6030-09-A01    368965
P-A-1-1011-14-G-01  368967
P-A-1-1014-01-G-05  368968
P-A-1-1017-02-D-01  368969
...

【问题讨论】:

  • pd.read_fwf(filename, header=None, skiprows=N),您必须将 N 设置为“无趣行”的数量

标签: python-3.x csv pandas


【解决方案1】:

假设你有以下数据文件:

This is a header of the textfile.The header has no columns.
This is a header of the textfile.The header has no columns.
This is a header of the textfile.The header has no columns.

P X1 6030-07-A01    368963
P-X1-6030-07-A01    368963
P-X1-6030-08-A01    368964
P-X1-6030-09-A01    368965
P-A-1-1011-14-G-01  368967
P-A-1-1014-01-G-05  368968
P-A-1-1017-02-D-01  368969

解决方案:让我们使用read_fwf()方法:

In [192]: fn = r'D:\temp\.data\data.fwf'

In [193]: pd.read_fwf(fn, widths=[19, 7], skiprows=4, header=None)
Out[193]:
                    0       1
0    P X1 6030-07-A01  368963   # NOTE: first column has spaces ...
1    P-X1-6030-07-A01  368963
2    P-X1-6030-08-A01  368964
3    P-X1-6030-09-A01  368965
4  P-A-1-1011-14-G-01  368967
5  P-A-1-1014-01-G-05  368968
6  P-A-1-1017-02-D-01  368969

【讨论】:

    【解决方案2】:
    pd.read_csv(filename, delim_whitespace=True, skiprows = number of rows to skip)
    

    【讨论】:

    • 谢谢。不幸的是,这不起作用。我没有说:有时第一列也包含空格,即它可能像 P X1 6030-07-A01 368963 那样是问题的根源吗?
    • 我只是将它修改为不跳过我的案例的行并将标题设置为无,它在我的案例中完美运行。
    猜你喜欢
    • 2018-07-05
    • 2017-01-03
    • 2014-12-30
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多