【问题标题】:How to read a csv in pandas with a missing delimiter (or - with additional delimiters)如何在缺少分隔符的熊猫中读取 csv(或 - 带有额外的分隔符)
【发布时间】:2020-11-09 16:24:57
【问题描述】:
import pandas as pd
from io import StringIO

csv_one = """\
one;two;three
1;2;3;
4;5;6;
"""
df1 = pd.read_csv(StringIO(csv), sep=";")

这个数据看起来像:

   one  two  three
1    2    3    NaN
4    5    6    NaN

想要的结果是:

   one  two  three
    1    2    3    
    4    5    6    

可以手动编辑 csv,但如果可能的话,我真的不想这样做。

R 中,函数read_delim 可以通过类似于read_delim( <path>, ";", escape_double = FALSE, trim_ws = TRUE) 的方式来管理它

【问题讨论】:

    标签: python pandas csv data-cleaning


    【解决方案1】:

    对我来说工作index_col=False参数:

    csv = """\
    one;two;three
    1;2;3;
    4;5;6;
    """
    df1 = pd.read_csv(StringIO(csv), sep=";", index_col=False)
    print (df1)
       one  two  three
    0    1    2      3
    1    4    5      6
    

    【讨论】:

    • 谢谢(我以为我已经尝试过了 - 但我担心我可能已经在源代码处编辑了 csv),熊猫有什么方法可以检测是否需要这样做?或者,我是否必须编写一个函数,在加载数据之前检查 CSV 行中的分隔符数量
    • @baxx - 我认为默认情况下是index_col=None,所以不幸的是这种类型的数据是必要的index_col=False - docs - Note: index_col=False can be used to force pandas to not use the first column as the index, e.g. when you have a malformed file with delimiters at the end of each line.
    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 2014-08-27
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多