首页 > 解决方案 > 从熊猫数据框中删除嵌套列

问题描述

我有一个包含嵌套数据的规范化数据框。

    timestamp               temp    weather
0   08/01/2021 00:00:00     17.82   [{'id': 800, 'main': 'Clear', 'description':... 
1   08/01/2021 01:00:00     17.12   [{'id': 800, 'main': 'Clear', 'description':... 
2   08/01/2021 02:00:00     16.53   [{'id': 800, 'main': 'Clear', 'description':... 

我已使用以下方法将嵌套数据提取到另一个数据框中:

 df_history_small = pd.json_normalize(data_history['hourly'], record_path='weather',meta=['dt','temp', 'humidity'], errors='ignore')

像这样我得到:

id  main    description         icon    dt                     temp     humidity
0   800     Clear   clear sky   01n     08/01/2021 00:00:00     17.82   69
1   800     Clear   clear sky   01n     08/01/2021 01:00:00     17.12   72
2   800     Clear   clear sky   01n     08/01/2021 02:00:00     16.53   74

现在我想删除列“主要”、描述和图标,但出现错误:

df_history_small = df_history_small.drop([('main', 'description', 'icon')], axis=1, inplace=True)

我怎样才能删除这些列。

谢谢

标签: pythonpandas

解决方案


drop按照@ALollz 的建议使用和修复您的语法:

>>> df.drop(['main', 'description', 'icon'], axis='columns')
    id                   dt   temp  humidity
0  800  08/01/2021 00:00:00  17.82        69
1  800  08/01/2021 01:00:00  17.12        72
2  800  08/01/2021 02:00:00  16.53        74

推荐阅读