且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 pandas 将一列词典拆分/展开为单独的列

更新时间:2023-11-18 20:58:52

要将字符串转换为实际字典,可以执行 df ['Pollutant Levels'].map(eval).之后,可以使用下面的解决方案将dict转换为不同的列.

To convert the string to an actual dict, you can do df['Pollutant Levels'].map(eval). Afterwards, the solution below can be used to convert the dict to different columns.

通过一个小例子,您可以使用 .apply(pd.Series):

Using a small example, you can use .apply(pd.Series):

In [2]: df = pd.DataFrame({'a':[1,2,3], 'b':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})

In [3]: df
Out[3]:
   a                   b
0  1           {u'c': 1}
1  2           {u'd': 3}
2  3  {u'c': 5, u'd': 6}

In [4]: df['b'].apply(pd.Series)
Out[4]:
     c    d
0  1.0  NaN
1  NaN  3.0
2  5.0  6.0

要将其与数据框的其余部分组合在一起,您可以 concat 具有上述结果的其他列:

To combine it with the rest of the dataframe, you can concat the other columns with the above result:

In [7]: pd.concat([df.drop(['b'], axis=1), df['b'].apply(pd.Series)], axis=1)
Out[7]:
   a    c    d
0  1  1.0  NaN
1  2  NaN  3.0
2  3  5.0  6.0


使用您的代码,如果我忽略了 iloc 部分,这也可以使用:

In [15]: pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
Out[15]:
   a    c    d
0  1  1.0  NaN
1  2  NaN  3.0
2  3  5.0  6.0