用 Python 编写一个程序,将数据帧行打印为带有元组值列表的 orderDict
假设您有一个数据框,并且带有元组列表的orderDict的结果是-
OrderedDict([('Index', 0), ('Name', 'Raj'), ('Age', 13), ('City', 'Chennai'), ('Mark', 80)]) OrderedDict([('Index', 1), ('Name', 'Ravi'), ('Age', 12), ('City', 'Delhi'), ('Mark', 90)]) OrderedDict([('Index', 2), ('Name', 'Ram'), ('Age', 13), ('City', 'Chennai'), ('Mark', 95)])
解决方案
为了解决这个问题,我们将按照下面给出的步骤-
定义数据框
设置for循环以使用setname='stud'中的函数访问所有行df.itertuples()
for row in df.itertuples(name='stud')
使用函数将所有行转换为带有元组列表的orderDict并将其保存为dict_row。最后打印值,rows._asdict()
dict_row = row._asdict() print(dict_row)
例子
让我们检查以下代码以获得更好的理解-
import pandas as pd Students = [('Raj', 13, 'Chennai', 80) , ('Ravi', 12, 'Delhi' , 90) , ('Ram', 13, 'Chennai', 95)] df = pd.DataFrame(Students, columns=['Name', 'Age', 'City', 'Mark']) print("DataFrame is:\n",df) for row in df.itertuples(name='stud'): dict_row = row._asdict() print(dict_row)
输出
DataFrame is: Name Age City Mark 0 Raj 13 Chennai 80 1 Ravi 12 Delhi 90 2 Ram 13 Chennai 95 OrderedDict([('Index', 0), ('Name', 'Raj'), ('Age', 13), ('City', 'Chennai'), ('Mark', 80)]) OrderedDict([('Index', 1), ('Name', 'Ravi'), ('Age', 12), ('City', 'Delhi'), ('Mark', 90)]) OrderedDict([('Index', 2), ('Name', 'Ram'), ('Age', 13), ('City', 'Chennai'), ('Mark', 95)])