pandas dataFrame 中的字典

Dictionary inside a pandas dataFrame

我有一个 pandas DataFrame,叫做 d,看起来像这样:

0      {'energies': [[0, 100, 1, 17.537183749262393, ...
1      {'energies': [[0, 100, 1, 0.5002560191707848, ...
2      {'energies': [[0, 100, 1, 0.833607984160617, 0...
3      {'energies': [[0, 100, 1, 2.0271986592908204, ...
4      {'energies': [[0, 100, 1, 0.20764045065127334,...
                             ...                        
119    {'energies': [[0, 100, 1, 0.6830323011861984, ...
120    {'energies': [[0, 100, 1, 3.9571018617595075, ...
121    {'energies': [[0, 100, 1, 4.815231137572439, 4...
122    {'energies': [[0, 100, 1, 33.556514163996766, ...
123    {'energies': [[0, 100, 1, 5.467475908262811, 5...
Name: results, Length: 124, dtype: object

如何删除字典?已尝试 d['energies'],但出现此错误:

Traceback (most recent call last):
  File "C:\LinearRegresseionEENX15\LinearRegression.py", line 15, in <module>
    print(d['energies'])
  File "C:\LinearRegresseionEENX15\lib\site-packages\pandas\core\series.py", line 958, in __getitem__
    return self._get_value(key)
  File "C:\LinearRegresseionEENX15\lib\site-packages\pandas\core\series.py", line 1069, in _get_value
    loc = self.index.get_loc(label)
  File "C:\LinearRegresseionEENX15\lib\site-packages\pandas\core\indexes\range.py", line 389, in get_loc
    raise KeyError(key)
KeyError: 'energies'

我可以使用 d[0]['energies'] 访问各个列表。但我想对整个数据框执行此操作。

您的问题与此类似:Split / Explode a column of dictionaries into separate columns with pandas

Pandas 有一个 json_normalize() 函数,可以将字典拆分成自己的列。假设您的字典列是数据框中的第一列:

df2 = pd.json_normalize(df[0])