用 Python 编写一个程序,将数据框行打印为带有元组值列表的 orderDict
pythonpandasserver side programmingprogramming
假设您有一个数据框,带有元组列表的 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 循环以使用集合内的 df.itertuples() 函数访问所有行name=’stud’
for row in df.itertuples(name='stud')
使用rows._asdict()函数将所有行转换为带有元组列表的orderDict,并将其保存为dict_row。最后打印值,
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)])