为了账号安全,请及时绑定邮箱和手机立即绑定

尝试在 pandas 数据框中使用 explode 不会导致数据发生变化

尝试在 pandas 数据框中使用 explode 不会导致数据发生变化

摇曳的蔷薇 2023-04-18 15:33:27
我正在尝试按照以下示例使用爆炸:#creating a dataframe for example:d = [{'A':3,'B':[{'id':'001'},{'id':'002'}]},    {'A':4,'B':[{'id':'003'},{'id':'004'}]},    {'A':5,'B':[{'id':'005'},{'id':'006'}]},    {'A':6,'B':[{'id':'007'},{'id':'008'}]}]df = pd.DataFrame(d)df    A   B0   3   [{'id': '001'}, {'id': '002'}]1   4   [{'id': '003'}, {'id': '004'}]2   5   [{'id': '005'}, {'id': '006'}]3   6   [{'id': '007'}, {'id': '008'}]#apply an explode to the column B and reset indexdf1 = df.explode('B')df1.reset_index(drop = True, inplace = True)df1# now it looks like this    A    B0   3   {'id': '001'}1   3   {'id': '002'}2   4   {'id': '003'}3   4   {'id': '004'}4   5   {'id': '005'}5   5   {'id': '006'}6   6   {'id': '007'}7   6   {'id': '008'}我的数据看起来像这样,非常相似:msaid   tracts0   159 [{"geoid":"02020000101"},{"geoid":"02020000204...1   160 [{"geoid":"26091060100"},{"geoid":"26125138100...2   161 [{"geoid":"01115040300"},{"geoid":"01015001700...3   163 [{"geoid":"72054580100"},{"geoid":"72054580200...4   162 [{"geoid":"55135100200"},{"geoid":"55135101200...问题是当我应用时,df.explode('tracts')数据框没有任何变化,我不确定为什么。非常感谢任何建议。这是我上面后者的代码:df = pd.read_excel('parse this.xlsx')df.head()    msaid   tracts0   159 [{"geoid":"02020000101"},{"geoid":"02020000204...1   160 [{"geoid":"26091060100"},{"geoid":"26125138100...2   161 [{"geoid":"01115040300"},{"geoid":"01015001700...3   163 [{"geoid":"72054580100"},{"geoid":"72054580200...4   162 [{"geoid":"55135100200"},{"geoid":"55135101200...
查看完整描述

2 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

使用ast模块将字符串转换为列表对象,然后使用explode


前任:


import ast


data = [{'A':3,'B':"[{'id':'001'},{'id':'002'}]"},

    {'A':4,'B':"[{'id':'003'},{'id':'004'}]"},

    {'A':5,'B':"[{'id':'005'},{'id':'006'}]"},

    {'A':6,'B':"[{'id':'007'},{'id':'008'}]"}]


df = pd.DataFrame(data)

df["B"] = df['B'].apply(ast.literal_eval)

df1 = df.explode('B')

df1.reset_index(drop = True, inplace = True)

print(df1)

输出:


   A              B

0  3  {'id': '001'}

1  3  {'id': '002'}

2  4  {'id': '003'}

3  4  {'id': '004'}

4  5  {'id': '005'}

5  5  {'id': '006'}

6  6  {'id': '007'}

7  6  {'id': '008'}


查看完整回答
反对 回复 2023-04-18
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

您需要更改类型以列出,然后您可以使用爆炸。

df=df.assign(**df['tracts'].apply(eval)).explode('tracts')


查看完整回答
反对 回复 2023-04-18
  • 2 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信