How to convert a pandas dataframe to namedtuple

China☆狼群 提交于 2019-12-20 05:48:07

问题


How to convert a pandas dataframe to namedtuple? This task is going towards multiprocessing work.

def df2namedtuple(df):
   return tuple(df.row)

回答1:


itertuples has option name and index. You may use them to return exact output as your posted function:

sample df:

df:
    A   B   C   D
0  32  70  39  66
1  89  30  31  80
2  21   5  74  63

list(df.itertuples(name='Row', index=False))

Out[1130]:
[Row(A=32, B=70, C=39, D=66),
 Row(A=89, B=30, C=31, D=80),
 Row(A=21, B=5, C=74, D=63)]



回答2:


Answer from Dan in https://groups.google.com/forum/#!topic/pydata/UaF6Y1LE5TI

from collections import namedtuple

def iternamedtuples(df):
    Row = namedtuple('Row', df.columns)
    for row in df.itertuples():
        yield Row(*row[1:])


来源:https://stackoverflow.com/questions/57011937/how-to-convert-a-pandas-dataframe-to-namedtuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!