简体   繁体   中英

Transforming pandas dataframe into a list of tuples considering index

I have a pandas dataframe with a structure like this:

rowNo | Column 1  | Column 2 | Column 3
0     |   Value   | 123.4    | 1
1     |   Value2  | 111.2    | 3

I need to transform it into a list of tuples considering the column rowNo as an index, resulting in this structure ( rowNo starts in 0 but the target list should shift the start to 1 ):

[(1, ['Value',123.4,1]), (2, ['Value2',111.2,3])]

Any inputs are very much appreciated.

Let us try

out = list(df.assign(rowNo = df['rowNo']+1).set_index('rowNo').agg(list,1).iteritems())
Out[95]: [(1, ['   Value   ', 123.4, 1]), (2, ['   Value2  ', 111.2, 3])]

Some list comprehension with * unpacking and to_numpy :

result = [(rowNo+1, [*rest]) for rowNo, *rest in df.reset_index(drop=True).to_numpy()]

You can also use:

data = list(zip(df.index+1, df.values.tolist()))

OUTPUT

[(1, ['Value', 123.4, 1]), (2, ['Value2', 111.2, 3])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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