[英]How to convert list of pair tuples in dataframe into columns
我有一個dataframe列,其中每個單元格數據看起來像:
[('a', '2000'),('b', '4000'),('d', '5000')]
。
有些將與c有4對。 如何將它們全部轉換為填充df['a'] , df['b'] , df['c'] , df['d']
?
另一種方法是:
l = [('a', '2000'),('b', '4000'),('d', '5000')]
df = pd.DataFrame([dict(l)])
如果您的數據就像元組的嵌套列表,請嘗試如下操作:
df = pd.DataFrame(list(map(dict, l)))
輸出將像:
a b d
0 2000 4000 5000
這不是矢量化的。 一種有效的解決方案是通過帶dict
list
+ map
將dict
列表提供給pd.DataFrame
構造函數:
s = pd.Series([[('a', '2000'),('b', '4000'),('d', '5000')],
[('a', '1000'),('b', '3000'),('c', '6000'),('d', '7000')]])
# example dataframe
df = pd.DataFrame(s, columns=['data'])
# convert list of tuples to dict for each element in series
res = pd.DataFrame(list(map(dict, df['data'])))
print(res)
a b c d
0 2000 4000 NaN 5000
1 1000 3000 6000 7000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.