我在pandas数据框中有一列,其中包含字典列表。我从csv文件加载了数据。
我在这里引用了类似的帖子,并尝试应用它。
但是我得到了错误
“ ValueError:DataFrame构造函数未正确调用!”
我想我在这里错过了一些东西。你能帮忙吗?
df_new = pd.DataFrame({"ID":[1,2],"Items":[{'string': '[{"barcode":"50","quantity":5,"unitPrice":1.01,"discount":1.5,"productName":"Chamallows"},{"barcode":"51","quantity":2,"unitPrice":2.01,"discount":1.0,"productName":"Haribo"}]', 'provided': 'string'},{'string': '[{"barcode":"52","quantity":3,"unitPrice":1.01,"discount":1.5,"productName":"Beer"}]', 'provided': 'string'}]})
这是我尝试过的
df = (pd.DataFrame(df_new['Items'].to_dict())).T
[pd.DataFrame(x) for x in df['string']]
这是预期的输出
ID barcode discount productName quantity unitPrice
1 50 1.5 Chamallows 5 1.01
1 51 1 Haribo 2 2.01
2 52 1.5 Beer 3 1.01
答案 0 :(得分:1)
尝试下面的代码,这将适合您的情况:
import ast
df_new = pd.DataFrame({"ID":[1,2],"Items":[{'string': '[{"barcode":"50","quantity":5,"unitPrice":1.01,"discount":1.5,"productName":"Chamallows"},{"barcode":"51","quantity":2,"unitPrice":2.01,"discount":1.0,"productName":"Haribo"}]', 'provided': 'string'},{'string': '[{"barcode":"52","quantity":3,"unitPrice":1.01,"discount":1.5,"productName":"Beer"}]', 'provided': 'string'}]})
df_ = pd.concat([df_new["ID"], ((pd.DataFrame(df_new['Items'].to_dict())).T).string.apply(ast.literal_eval)],axis=1).explode("string")
df_output = pd.concat([df_["ID"],pd.DataFrame(df_['string'].values.tolist(), index=df_.index)],axis=1)
输出:
ID barcode quantity unitPrice discount productName
0 1 50 5 1.01 1.5 Chamallows
0 1 51 2 2.01 1.0 Haribo
1 2 52 3 1.01 1.5 Beer
答案 1 :(得分:0)
问题在于列表理解
const routes: Routes = [
{path: '', component: HomeComponent,
children: [
{path: 'other', component: OtherComponent}
],
},
{path: ':param', component: HomeComponent},
];
[pd.DataFrame(x) for x in df['string']]
是字符串,而不是可迭代的/ list。因此,DataFrame构造函数将无法接受它。
一种方法是将字符串加载为json。但是您需要验证它是否可以解决所有情况。
x