获得相同输出的更优雅、更有效的方式



我有一个df:

info
{"any_name":{"value":["5"], "ref":"any text"}, "another_name":{"value":["2"], "ref":"any text"}
{"any_name":{"value":["1"], "ref":"any text"}, "another_name":{"value":["12"], "ref":"any text"}

这个列的dtype是:

df['info'].apply(type) =>   <class 'str'>

我想创建一个数据帧来得到这个输出:

any_name  another_any_name
5          2
1          12

我的解决方案是:

A=list(df['answers'])
J=[]
for i in range(0,len(A)):
D=eval(A[i])
foo = {k: v['value'] for k, v in D.items() if k in list_to_filter_columns}
J.append(foo)
out=pd.DataFrame(J)

代码将来自value的值转换为数字,因为它们是一个元素列表

outt = outt.apply(lambda x: x.str[0])
outt = outt.apply(pd.to_numeric)
outt.head(2)

上面的解决方案工作得很好。

我想知道是否有更优雅的方法来得到相同的结果。我认为上面的代码是非常低效和不优雅的。有更好的方法吗?

不需要循环,您可以使用pandas.json_normalize:

import ast
df["info"] = df["info"].apply(lambda x: ast.literal_eval(x+"}"))
​
out = (
pd.json_normalize(df["info"])
.filter(regex="value$")
.astype(str)
.apply(lambda x: x.str.strip("['']"))
)
​
out.columns = out.columns.str.replace(".value", "", regex=True)

#输出
​
print(out)
any_name another_name
0        5            2
1        1           12

最新更新