繁体   English   中英

如何将从 csv 文件中读取的 dataframe 打印为字典格式?

[英]How to print a dataframe which is read from a csv file into dictionary format?

I turned the data in a csv file into a dataframe by using Pandas then proceeded to print the dataframe into dictionary format by using Ordereddict.

但是,当我这样做时,每行的索引号都丢失了,是保留索引号还是无论如何要使用索引号达到相同的结果?

而且我不完全确定 zip() 和 tolist() 的部分,任何人都可以解释它们的用法吗?

我的代码:

import pandas as pd
from collections import OrderedDict
import collections

df = pd.read_csv('for_testing.csv')


for i, row in df.iterrows():
  d = OrderedDict(zip(row.index.tolist(), row.tolist()))
  print(d)

Output:

OrderedDict([('First Name', 'Kate'), ('Last Name', 'Rose'), ('Occupation', 'Teacher'), ('Age', 24), ('Number', 87)])
OrderedDict([('First Name', 'James'), ('Last Name', 'Smith'), ('Occupation', 'Cook'), ('Age', 35), ('Number', 487)])
OrderedDict([('First Name', 'Nick'), ('Last Name', 'Carter'), ('Occupation', 'Writer'), ('Age', 44), ('Number', 896)])
OrderedDict([('First Name', 'Ray'), ('Last Name', 'Johnson'), ('Occupation', 'Designer'), ('Age', 34), ('Number', 412)])
OrderedDict([('First Name', 'Jay'), ('Last Name', 'Law'), ('Occupation', 'Unemployed'), ('Age', 25), ('Number', 123)])

我希望 Output 是这样的:

1. OrderedDict([('First Name', 'Kate'), ('Last Name', 'Rose'), ('Occupation', 'Teacher'), ('Age', 24), ('Number', 87)])
2. OrderedDict([('First Name', 'James'), ('Last Name', 'Smith'), ('Occupation', 'Cook'), ('Age', 35), ('Number', 487)])
3. OrderedDict([('First Name', 'Nick'), ('Last Name', 'Carter'), ('Occupation', 'Writer'), ('Age', 44), ('Number', 896)])
4. OrderedDict([('First Name', 'Ray'), ('Last Name', 'Johnson'), ('Occupation', 'Designer'), ('Age', 34), ('Number', 412)])
5. OrderedDict([('First Name', 'Jay'), ('Last Name', 'Law'), ('Occupation', 'Unemployed'), ('Age', 25), ('Number', 123)])

编辑:我注意到一个问题,当我尝试通过用户输入触发打印时,它只显示ordereddict dataframe的最后一行,而不是整个ordereddict dataframe:

新代码:

import pandas as pd
from collections import OrderedDict
import collections

df = pd.read_csv('for_testing.csv')

def main():
  choice = input("type sth ")
  
  if choice == '1':
      for i, row in df.iterrows():
        d = OrderedDict(zip(row.index.tolist(), row.tolist()))
      print(d)


main()

新 Output:

type sth 1
OrderedDict([('First Name', 'Jay'), ('Last Name', 'Law'), ('Occupation', 'Unemployed'), ('Age', 25), ('Number', 123)])

每次在循环中定义字典时,都会覆盖字典。 您可以首先在循环之外定义一个空字典,然后在循环中为其分配值。 使用OrderedDict ,它应该按照您分配的顺序保留项目:

d = OrderedDict()
for i, row in df.iterrows():
    d[i] = list(zip(row.index.tolist(), row.tolist()))
print(d)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM