【问题标题】:Print DataFrame as comma separated values将 DataFrame 打印为逗号分隔值
【发布时间】:2020-02-11 00:44:37
【问题描述】:

我有一个类似于以下内容的 Pandas DataFrame:

import pandas as pd

city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
population = pd.Series([852469, 1015785, 485199])

df = pd.DataFrame({'City name': city_names, 'Population': population})

我正在尝试得到这个输出:

San Fransisco, 852469

San Jose, 1015785

Sacramento, 485199

【问题讨论】:

  • 你有没有尝试过,做过什么研究?
  • 请注意,如果逗号后面没有空格,df.to_csv(index=False) 也可以使用。
  • 好点@MateenUlhaq,这让我想知道OP是否首先想要CSV输出。

标签: python python-3.x pandas


【解决方案1】:
>>> s = "\n".join(", ".join(map(str, xs)) for xs in df.itertuples(index=False))
>>> print(s)

San Francisco, 852469
San Jose, 1015785
Sacramento, 485199

【讨论】:

  • 由于索引被丢弃,你可以从.iterrows()切换到.itertuples(index=False)。性能也可能会好得多。
  • @AMC 谢谢,我进行了一些性能测试,它看起来快了 60 倍。此外,它似乎比“方法 2”(1.3 倍)和“方法 1”(5 倍)稍快。
  • 另外,它似乎比“方法 2”(1.3 倍)和“方法 1”(5 倍)稍快。 嗯,我有点很惊讶,因为我的第二种方法和你的很相似。
【解决方案2】:

我想避免.iterrows(),因为它往往很迟钝。


方法一:

'\n'.join(df.astype(str).apply(lambda x: ', '.join(x), axis=1))

方法二:

'\n'.join([', '.join(elem) for elem in df.astype(str).itertuples(index=False)])

【讨论】:

    【解决方案3】:

    如果我理解你的问题,下面会打印一本字典。

    import pandas as pd
    
    city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
    population = pd.Series([852469, 1015785, 485199])
    
    df = pd.DataFrame({ 'City name': city_names, 'Population': population })
    
    the_dict = df.to_dict()
    
    

    这将打印一个字典

    print(the_dict)
    
    {'City name': {0: 'San Francisco', 1: 'San Jose', 2: 'Sacramento'}, 'Population': {0: 852469, 1: 1015785, 2: 485199}}
    

    说你想要的输出看起来像逗号分隔的值。

    【讨论】:

    • 好吧,也许我问错了。如何一次打印一行?
    猜你喜欢
    • 2017-12-19
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    相关资源
    最近更新 更多