猿问

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

我正在尝试按照以下示例使用爆炸:


#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   B

0   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 index


df1 = df.explode('B')

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

df1


# now it looks like this

    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'}

我的数据看起来像这样,非常相似:


msaid   tracts

0   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   tracts

0   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...


摇曳的蔷薇
浏览 195回答 2
2回答

喵喵时光机

使用ast模块将字符串转换为列表对象,然后使用explode前任:import astdata = [{'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              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'}

明月笑刀无情

您需要更改类型以列出,然后您可以使用爆炸。df=df.assign(**df['tracts'].apply(eval)).explode('tracts')
随时随地看视频慕课网APP

相关分类

Python
我要回答