简体   繁体   English

如何将熊猫数据框转换为命名元组

[英]How to convert a pandas dataframe to namedtuple

How to convert a pandas dataframe to namedtuple?如何将pandas数据帧转换为namedtuple? This task is going towards multiprocessing work.此任务将进行多处理工作。

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

itertuples has option name and index . itertuples有选项nameindex You may use them to return exact output as your posted function:您可以使用它们将准确的输出作为您发布的函数返回:

sample df:示例 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)]

Answer from Dan in https://groups.google.com/forum/#!topic/pydata/UaF6Y1LE5TI丹在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:])

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

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