简体   繁体   English

如何将元组列表转换为 Pandas 数据框,以便每个元组的第一个值代表一列?

[英]How can I transform a list of tuples into a pandas dataframe so that the first value of each tuple represents a column?

I would like to transform my list of tuples so that the first element of each tuple represents 2 different columns.我想转换我的元组列表,以便每个元组的第一个元素代表 2 个不同的列。 The second element of each tuple should represent the values that correspond to the columns in the pandas df.每个元组的第二个元素应该表示与 pandas df 中的列对应的值。

My current list of tuples:我当前的元组列表:


list_tuples = [('G', 9.8), ('B', 4.2), ('G', 9.6), ('B', 2.3), ('G',7.6), ('B', 3.1)]

Desired output:期望的输出:


            G        B   
           9.8      4.2      
           9.6      2.3      
           7.6      3.1      

The code I currently have which does not give desired output:我目前拥有的代码没有提供所需的输出:


df = pd.DataFrame(list_tuples, columns=['G', 'B'])

Use defaultdict for convert list of tuples for dictionary of lists and then pass it to DataFrame constructor:使用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

Convert it to a dictionary, create your dataframe and clean it up with DataFrame.drop_duplicates and DataFrame.bfill :将其转换为字典,创建数据DataFrame.drop_duplicates并使用DataFrame.drop_duplicatesDataFrame.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.

相关问题 如何使用每个元组的第一个值作为键将六个元组列表连接到 Pandas 数据框中? - How do I join six list of tuples into a pandas dataframe using the first value of each tuple as the key? 我可以将 Pandas dataframe 转换为元组列表吗? - Can I transform a Pandas dataframe into a list of tuples? 如何在 Python 中的元组列表中对每个元组中的第一个值求和? - How do I sum the first value in each tuple in a list of tuples in Python? 如何根据每个元组中第一个数字的值从元组列表中弹出项目? - How do I pop item off a list of tuples, based on the value of the first number in each tuple? 如何通过 class 方法迭代元组列表中每个元组的第一个元素? - How can I iterate the first element of each tuple in a list of tuples through a class method? 如何用元组中每个元组的第一个值构成一个新元组? - How to form a new tuple with the first value of each tuple of a tuple of tuples? 如何将元组列表转换为元组? - How to transform list of tuples into a tuple? 将包含字典列表的列的 pandas dataframe 转换为元组的元组 - Convert pandas dataframe with column containing list of dictionaries to tuple of tuples 我可以 pivot 基于元组列表的 pandas dataframe 中的一列吗? - Can I pivot a column in a pandas dataframe based on a list of tuples? 将元组列表转换为dataframe - 其中元组的第一个元素是列名 - Convert list of tuples to dataframe - where first element of tuple is column name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM