![](/img/trans.png)
[英]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.