【问题标题】:python: print multiple dictionaries and strings line by linepython:逐行打印多个字典和字符串
【发布时间】:2021-05-26 13:37:36
【问题描述】:

我有一个包含不同列的数据框,我计算了每列的 value_counts 并将它们转换为_dict。我现在想逐行打印它们,并添加一些描述每个字典的字符串,如下所示:

print( 'Names and counts',
       '\n',
       df['names'].value_counts()[:3].to_dict(),
       '\n',
       'Last names and counts',
       '\n',
       df['last names'].value_counts()[:3].to_dict(),
       'Staff names and counts',
       '\n',
       df['staff_names'].value_counts()[:3].to_dict(),
       '\n',
       'Staff last names and counts',
       '\n',
       df['staff last names'].value_counts()[:3].to_dict())

Current output:
 Names and counts
{"Jack": 20, "John": 10, "Samuel": 9}

 Last names and counts
{"Brown": 25, "Smith": 30, "Jackson": 5}

 Staff names and counts
{"Mars": 22, "Joshua": 20, "Simon": 8}

 Staff last names and counts
{"Bernard": 27, "Kohlen": 16, "Dimun": 7}

所以我希望输出如下所示:

Desired output:

 Names and counts
{"Jack": 20,
 "John": 10,
 "Samuel": 9}

 Last names and counts
{"Brown": 25,
 "Smith": 30,
 "Jackson": 5}

 Staff names and counts
{"Mars": 22,
 "Joshua": 20,
 "Simon": 8}

 Staff last names and counts
{"Bernard": 27,
 "Kohlen": 16,
 "Dimun": 7}

我已经尝试使用 pprint() 或 print() 来代替,但这会引发错误。

我也尝试添加 print(*each dictionary, sep= '\n') 但它只返回索引并删除数字(计数)

【问题讨论】:

  • 你当前的输出是多少?
  • 当前输出为:一行中的所有字典项
  • 好的,我有一个解决方案..

标签: python pandas dictionary printing pprint


【解决方案1】:

试试这个,

import json
print( 'Names and counts',
       '\n',
       json.dumps(df['names'].value_counts()[:3].to_dict(),indent=2),
       '\n',
       'Last names and counts',
       '\n',
       json.dumps(df['last names'].value_counts()[:3].to_dict(),indent=2),
       'Staff names and counts',
       '\n',
       json.dumps(df['staff_names'].value_counts()[:3].to_dict(),indent=2),
       '\n',
       'Staff last names and counts',
       '\n',
       json.dumps(df['staff last names'].value_counts()[:3].to_dict(),indent=2)

将 indent 参数更改为更大的数字以获得更好的格式..

注意:经过 Creator 测试并且工作正常。

【讨论】:

  • 请测试代码并检查您是否达到了最终目标..
  • 非常感谢,它就像魔术一样工作 :)
  • 太棒了!祝你好运。
【解决方案2】:

使用json.dumpsindent = 字典级别:

for c in df.columns:
    print(f"{c} and counts\n{json.dumps(df[c].value_counts()[:3].to_dict(),indent=2)}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    相关资源
    最近更新 更多