[英]Convert list to dataframe (Pandas)
有什么辦法可以將這種類型的輸出轉換為 Dataframe 嗎? 輸出:
[['A', 'B'], ['Orange', 'Apple']]
[['C', 'D'], ['Coconut', 'Lemon']]
[['E'], ['Mango', 'Strawberry']]
I want to turn the output into a dataframe like this:
` x1 X2
0 A,B Orange, Apple
1 C,D Coconut, Lemon
2 E Mango, Strawberry`
只需將此數據添加到列表中
import pandas as pd
data = [[['A', 'B'], ['Orange', 'Apple']],
[['C', 'D'], ['Coconut', 'Lemon']],
[['E'], ['Mango', 'Strawberry']]]
df = pd.DataFrame(data, columns=['x1', 'x2'])
所以 df 看起來像
x1 x2
0 [A, B] [Orange, Apple]
1 [C, D] [Coconut, Lemon]
2 [E] [Mango, Strawberry]
如果您的起始數據在列表中,並且您想用逗號連接每個列表,這應該有效:
l = [[['A', 'B'], ['Orange', 'Apple']],
[['C', 'D'], ['Coconut', 'Lemon']],
[['E'], ['Mango', 'Strawberry']]]
df = pd.DataFrame([[', '.join(v) for v in i] for i in l],columns = ['x1','x2'])
stack()
和str.join()
也是一個選項:
df = pd.DataFrame(l,columns = ['x1','x2']).stack().str.join(', ').unstack()
輸出:
x1 x2
0 A, B Orange, Apple
1 C, D Coconut, Lemon
2 E Mango, Strawberry
簡單修復:
pd.DataFrame(
{"x1":[["A", "B"], ["C", "D"], ["E"]],
"x2":[["Orange", "Apple"], ["Coconut", "Lemon"], ["Mango", "Strawberry"]]}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.