pandas datafram中的Dictionary列

2024-03-28 22:37:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv,我正在读取到熊猫数据帧中。但是其中一列是字典的形式。下面是一个例子:

ColA, ColB, ColC, ColdD
20, 30, {"ab":"1", "we":"2", "as":"3"},"String"

如何将其转换为如下所示的数据帧:

ColA, ColB, AB, WE, AS, ColdD
20, 30, "1", "2", "3", "String"

编辑 我解决了这个问题,它看起来像这样,但它是一个需要解析的字符串,而不是dict对象。


Tags: csv数据string字典abas形式例子
2条回答

根据https://stackoverflow.com/a/38231651/454773,可以使用.apply(pd.Series)将包含dict的列映射到新列,然后将这些新列连接回原始数据帧减去包含dict的原始列:

dw=pd.DataFrame( [[20, 30, {"ab":"1", "we":"2", "as":"3"},"String"]],
                columns=['ColA', 'ColB', 'ColC', 'ColdD'])
pd.concat([dw.drop(['ColC'], axis=1), dw['ColC'].apply(pd.Series)], axis=1)

返回:

ColA    ColB    ColdD   ab  as  we
20      30      String  1   3   2

所以从你的单列df开始

    Col A   Col B   Col C                           Col D
0   20      30      {u'we': 2, u'ab': 1, u'as': 3}  String1

编辑:根据OP的注释,我假设我们需要先转换字符串

import ast
df["ColC"] =  df["ColC"].map(lambda d : ast.literal_eval(d))

然后我们将Col C转换成dict,将其转置,然后将其加入到原始df中

dfNew = df.join(pd.DataFrame(df["Col C"].to_dict()).T)
dfNew

给你这个

    Col A   Col B   Col C                           Col D   ab  as  we
0   20      30      {u'we': 2, u'ab': 1, u'as': 3}  String1 1   3   2

然后在dfNew中选择所需的列

dfNew[["Col A", "Col B", "ab", "we", "as", "Col D"]]

    Col A   Col B   ab  we  as  Col D
0   20      30      1   2   3   String1

相关问题 更多 >