简体   繁体   English

将 pandas dataframe 转换为考虑索引的元组列表

[英]Transforming pandas dataframe into a list of tuples considering index

I have a pandas dataframe with a structure like this:我有一个 pandas dataframe 结构如下:

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 ):我需要将它转换为一个元组列表,考虑列rowNo作为索引,从而产生这个结构( rowNo0开始,但目标列表应该将开始移到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 :一些带有* unpacking unpacking 和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])]

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

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