Reputation: 3961
How to convert a pandas dataframe to namedtuple? This task is going towards multiprocessing work.
def df2namedtuple(df):
return tuple(df.row)
Upvotes: 5
Views: 7578
Reputation: 25239
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)]
Upvotes: 15
Reputation: 3961
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:])
Upvotes: 2