[英]Can I transform a Pandas dataframe into a list of tuples?
I have a Pandas dataframe with some correlations in the form of:我有一个 Pandas dataframe 与以下形式的一些相关性:
A B
D 0.78 0.49
E 0.93 0.67
Is there a fast way in Python to get a list of tuples like: [(A, D, 0.78), (A, E, 0.93), (B, D, 0.49), (B, E, 0.67)] Python 中是否有一种快速的方法来获取元组列表,例如:[(A, D, 0.78), (A, E, 0.93), (B, D, 0.49), (B, E, 0.67)]
Thanks in advance for your help.在此先感谢您的帮助。
Use DataFrame.unstack
for reshape, then convert Series
to DataFrame
and last convert nested lists to tuples:使用DataFrame.unstack
进行整形,然后将Series
转换为DataFrame
并最后将嵌套列表转换为元组:
L = [tuple(x) for x in df.unstack().reset_index().to_numpy()]
Or:或者:
L = list(map(tuple, df.unstack().reset_index().to_numpy()))
Another idea, thank you @Datanovice:另一个想法,谢谢@Datanovice:
L = list(df.unstack().reset_index().itertuples(name=None,index=None))
print (L)
[('A', 'D', 0.78), ('A', 'E', 0.93), ('B', 'D', 0.49), ('B', 'E', 0.67)]
If order should be swapped, thank you @Ch3steR:如果应该交换订单,谢谢@Ch3steR:
L = list(df.reset_index().melt(id_vars='index').itertuples(name=None,index=None))
print (L)
[('D', 'A', 0.78), ('E', 'A', 0.93), ('D', 'B', 0.49), ('E', 'B', 0.67)]
Try this,尝试这个,
import pandas as pd
dt = {'a': [1, 2], 'b': [3, 4]}
cols = ['a', 'b']
rows = ['d', 'e']
df = pd.DataFrame(dt, index=rows)
print(df)
a b
d 1 3
e 2 4
result = []
for c in cols:
for r in rows:
result.append((c, r, df[c][r]))
print(result)
[('a', 'd', 1), ('a', 'e', 2), ('b', 'd', 3), ('b', 'e', 4)]
Sure, it is possible.当然,这是可能的。 I would do that like this:我会这样做:
import pandas as pd
import numpy as np
# Creating example DF
tab = pd.DataFrame(data={'A': (1,2), 'B': (3,4)})
tab.index=['C', 'D']
# Values to tuples
np.array(tab.apply(lambda x: [(x.index[i], x.name,y) for i, y in enumerate(x)])).ravel()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.