[英]How do I join six list of tuples into a pandas dataframe using the first value of each tuple as the key?
[英]How can I transform a list of tuples into a pandas dataframe so that the first value of each tuple represents a column?
我想转换我的元组列表,以便每个元组的第一个元素代表 2 个不同的列。 每个元组的第二个元素应该表示与 pandas df 中的列对应的值。
我当前的元组列表:
list_tuples = [('G', 9.8), ('B', 4.2), ('G', 9.6), ('B', 2.3), ('G',7.6), ('B', 3.1)]
期望的输出:
G B
9.8 4.2
9.6 2.3
7.6 3.1
我目前拥有的代码没有提供所需的输出:
df = pd.DataFrame(list_tuples, columns=['G', 'B'])
使用defaultdict
转换列表字典的元组列表,然后将其传递给DataFrame
构造函数:
from collections import defaultdict
d = defaultdict(list)
for a, b in list_tuples:
d[a].append(b)
df = pd.DataFrame(d)
print (df)
G B
0 9.8 4.2
1 9.6 2.3
2 7.6 3.1
将其转换为字典,创建数据DataFrame.drop_duplicates
并使用DataFrame.drop_duplicates
和DataFrame.bfill
清理它:
list_tuples = [('G', 9.8), ('B', 4.2), ('G', 9.6), ('B', 2.3), ('G',7.6), ('B', 3.1)]
df = (pd.DataFrame([{col1:val} for col1, val in list_tuples])
.bfill()
.drop_duplicates('B')
.reset_index(drop=True)
)
G B
0 9.80 4.20
1 9.60 2.30
2 7.60 3.10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.