【问题标题】:Create Pandas DataFrame from a string从字符串创建 Pandas DataFrame
【发布时间】:2021-12-28 18:23:26
【问题描述】:

为了测试一些功能,我想从一个字符串创建一个DataFrame。假设我的测试数据如下所示:

TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""

将这些数据读入 Pandas DataFrame 的最简单方法是什么?

【问题讨论】:

    标签: python string pandas csv csv-import


    【解决方案1】:

    一个简单的方法是使用StringIO.StringIO (python2)io.StringIO (python3) 并将其传递给pandas.read_csv 函数。例如:

    import sys
    if sys.version_info[0] < 3: 
        from StringIO import StringIO
    else:
        from io import StringIO
    
    import pandas as pd
    
    TESTDATA = StringIO("""col1;col2;col3
        1;4.4;99
        2;4.5;200
        3;4.7;65
        4;3.2;140
        """)
    
    df = pd.read_csv(TESTDATA, sep=";")
    

    【讨论】:

    • 仅供参考 - pd.read_table() 是一个等效函数,只是命名法稍微好一点:df = pd.read_table(TESTDATA, sep=";")
    • @AntonvBR 注意到可以使用pandas.compat.StringIO。这样我们就不必单独导入StringIO。但是,根据pandas.pydata.org/pandas-docs/stable/api.html?highlight=compatpandas.compat 包被认为是私有的,所以现在保留答案。
    • 是时候整理一下哪个导入了:Should we use pandas.compat.StringIO or Python 2/3 StringIO?
    • 如果您使用df.to_csv(TESTDATA) 创建TESTDATA,请使用TESTDATA.seek(0)
    • 我收到“错误标记数据。 C 错误:预计第 26 行中有 2 个字段,看到 12\n',)
    【解决方案2】:

    此答案适用于手动输入字符串时,而不是从某处读取时。

    传统的可变宽度 CSV 无法将数据存储为字符串变量。特别是在 .py 文件中使用时,请考虑使用固定宽度的管道分隔数据。各种 IDE 和编辑器可能有一个插件来将管道分隔的文本格式化成一个整洁的表格。

    使用read_csv

    将以下内容存储在实用程序模块中,例如util/pandas.py。函数的文档字符串中包含一个示例。

    import io
    import re
    
    import pandas as pd
    
    
    def read_psv(str_input: str, **kwargs) -> pd.DataFrame:
        """Read a Pandas object from a pipe-separated table contained within a string.
    
        Input example:
            | int_score | ext_score | eligible |
            |           | 701       | True     |
            | 221.3     | 0         | False    |
            |           | 576       | True     |
            | 300       | 600       | True     |
    
        The leading and trailing pipes are optional, but if one is present,
        so must be the other.
    
        `kwargs` are passed to `read_csv`. They must not include `sep`.
    
        In PyCharm, the "Pipe Table Formatter" plugin has a "Format" feature that can 
        be used to neatly format a table.
    
        Ref: https://stackoverflow.com/a/46471952/
        """
    
        substitutions = [
            ('^ *', ''),  # Remove leading spaces
            (' *$', ''),  # Remove trailing spaces
            (r' *\| *', '|'),  # Remove spaces between columns
        ]
        if all(line.lstrip().startswith('|') and line.rstrip().endswith('|') for line in str_input.strip().split('\n')):
            substitutions.extend([
                (r'^\|', ''),  # Remove redundant leading delimiter
                (r'\|$', ''),  # Remove redundant trailing delimiter
            ])
        for pattern, replacement in substitutions:
            str_input = re.sub(pattern, replacement, str_input, flags=re.MULTILINE)
        return pd.read_csv(io.StringIO(str_input), sep='|', **kwargs)
    
    

    无效的替代方案

    下面的代码不能正常工作,因为它在左右两边都添加了一个空列。

    df = pd.read_csv(io.StringIO(df_str), sep=r'\s*\|\s*', engine='python')
    

    至于read_fwf,它doesn't actually use 有很多read_csv 接受和使用的可选kwargs。因此,它根本不应该用于管道分隔的数据。

    【讨论】:

    • 我发现(通过反复试验)read_fwf 接受的read_csvs 参数比记录的要多,但some have no effect 确实如此。
    【解决方案3】:

    一种快速简便的交互式工作解决方案是通过从剪贴板加载数据来复制和粘贴文本。

    用鼠标选择字符串的内容:

    在 Python shell 中使用read_clipboard()

    >>> pd.read_clipboard()
      col1;col2;col3
    0       1;4.4;99
    1      2;4.5;200
    2       3;4.7;65
    3      4;3.2;140
    

    使用适当的分隔符:

    >>> pd.read_clipboard(sep=';')
       col1  col2  col3
    0     1   4.4    99
    1     2   4.5   200
    2     3   4.7    65
    3     4   3.2   140
    
    >>> df = pd.read_clipboard(sep=';') # save to dataframe
    

    【讨论】:

    • 不利于再现性,但在其他方面是一个非常简洁的解决方案!
    【解决方案4】:

    拆分方法

    data = input_string
    df = pd.DataFrame([x.split(';') for x in data.split('\n')])
    print(df)
    

    【讨论】:

    • 如果您希望第一行用于列名,请将第二行更改为:df = pd.DataFrame([x.split(';') for x in data.split('\n')[1:]], columns=[x for x in data.split('\n')[0].split(';')])
    • 这是错误的,因为在 CSV 文件中,换行符 (\n) 可以是字段的一部分。
    • 这不是很健壮,大多数人接受的答案会更好。 thomasburette.com/blog/2014/05/25/…
    【解决方案5】:

    最简单的方法是将其保存到临时文件然后读取:

    import pandas as pd
    
    CSV_FILE_NAME = 'temp_file.csv'  # Consider creating temp file, look URL below
    with open(CSV_FILE_NAME, 'w') as outfile:
        outfile.write(TESTDATA)
    df = pd.read_csv(CSV_FILE_NAME, sep=';')
    

    创建临时文件的正确方法:How can I create a tmp file in Python?

    【讨论】:

    • 如果没有创建文件的权限怎么办?
    • 在我看来,这不再是最简单的情况了。请注意,问题中明确说明了“最简单”。
    【解决方案6】:

    一行,但先导入IO

    import pandas as pd
    import io   
    
    TESTDATA="""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """
    
    df = pd.read_csv(io.StringIO(TESTDATA), sep=";")
    print(df)
    

    【讨论】:

    • 这与接受的答案有什么区别?除了将 io 操作移动到 read_csv 之外,这没有什么区别......请始终检查是否尚未发布类似的答案,冗余是不必要的。
    【解决方案7】:

    对象:取字符串制作数据框。

    解决方案

    def str2frame(estr, sep = ',', lineterm = '\n', set_header = True):
        dat = [x.split(sep) for x in estr.split(lineterm)][1:-1]
        cdf = pd.DataFrame(dat)
        if set_header:
            cdf = cdf.T.set_index(0, drop = True).T # flip, set ix, flip back
        return cdf
    

    示例

    estr = """
    sym,date,strike,type
    APPLE,20MAY20,50.0,Malus
    ORANGE,22JUL20,50.0,Rutaceae
    """
    
    cdf = str2frame(estr)
    
    
    print(cdf)
    0     sym     date strike      type
    1   APPLE  20MAY20   50.0     Malus
    2  ORANGE  22JUL20   50.0  Rutaceae
    

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 2019-02-10
      • 2015-10-29
      • 2019-07-08
      • 2017-02-19
      • 2018-12-02
      • 2017-10-31
      相关资源
      最近更新 更多