有時候會遇到一種情況,就是在dataframe的某一列中是比較複雜的數據結構,比如一個dict,或者一個list,或者一個list of list,其實都有很好的辦法可以解決的,不需要用多重的for循環,這裏放兩個例子:
Splitting a list in a Pandas cell into multiple columns
源dataframe
df = pd.DataFrame(data=[[[8,10,12], 'A'],
[[7,9,11], 'B']])
目標效果:
0 1 2 3
0 8 10 12 A
1 7 9 11 B
其實很簡單,只需要一行代碼就能解決:
df[0].apply(pd.Series)
# 0 1 2
#0 8 10 12
#1 7 9 11
Update: To keep other columns of the data frame, you can concatenate the result with the columns you want to keep:
pd.concat([df[0].apply(pd.Series), df[1]], axis = 1)
# 0 1 2 1
#0 8 10 12 A
#1 7 9 11 B
另外這裏還有其他的幾個博客,可以用於參考:
How to convert lists to a dataframe
Convert a list of lists into a Pandas Dataframe
有一個很簡單的函數:
nums =
[[1,2],
[3,4]]
a = sum(nums,[]) 一句話
除了轉換成多列,還可以轉換成行:
How to split a list inside a Dataframe cell into rows in Pandas
很好用吧
更新:
此外,如果在一列中出現的不是上述的list of list,而是dict,其實也很好解決,可以使用這一行代碼
{'bids': [[1.0002, 612.52], [0.9998, 11.6], [0...
1 {'bids': [[11321.12, 0.005634999999999999], [1...
2 {'bids': [[0.46072, 1500], [0.46061, 1500], [0...
3 {'bids': [[11329.89, 0.0011], [11324.46, 0.069...
4 {'bids': [[0.027233, 0.606], [0.027232, 0.5660...
pd.DataFrame(list(meta_df['meta_data']))