python-3.x - 使用字典键作为标题将字典数据从数据帧列获取到新的数据帧
问题描述
我有一个数据框,其中一列充满了字典:
Col
Index1 {"A":1, "B":2, "C":3}
Index2 {"A":4, "B":5, "C":6}
.
.
.
我想要一个新的数据框:
A B C
Index1 1 2 3
Index2 4 5 6
.
.
.
如您所见,DF 列中的 dict 键应该成为新的标题。理想情况下,我想保留索引。
我试图用这个from_dict
从该列创建一个新的数据框,但它不起作用。
IE
new_DF = pd.DataFrame.from_dict(old_DF[Col])
我得到了错误:ValueError: If using all scalar values, you must pass an index
我也尝试了其他方法无济于事。任何指导将不胜感激。
解决方案
apply
与 一起使用pd.Series
:
>>> df['Col'].apply(pd.Series)
A B C
Index1 1 2 3
Index2 4 5 6
>>>
或使用pd.json_normalize
:
>>> pd.json_normalize(df['Col']).set_axis(df.index)
A B C
Index1 1 2 3
Index2 4 5 6
>>>
或尝试添加tolist
:
>>> pd.DataFrame(df['Col'].tolist(), index=df.index)
A B C
Index1 1 2 3
Index2 4 5 6
>>>
编辑:
如果您的列是字符串类型,请尝试:
from ast import literal_eval
df['Col'].map(literal_eval).apply(pd.Series)
A B C
Index1 1 2 3
Index2 4 5 6
推荐阅读
- php - 使用提交按钮通过 PHP 插入 MySQL 数据库?
- android - 可以根据 LatLng 放置标记的 CustomMapView
- windows - 发送一次按键,但好像按键被按下
- angular - 测试在调试元素之外注入的 Angular 对话框窗口
- php - 重定向以重命名远程图像以绕过adblock
- python - 计算与pyspark数据框中特定值匹配的键值
- python - Keras ValueError:形状 (None, 1) 和 (None, 48, 48, 96) 不兼容
- pandas - 当其他列为空时,如何获取列的最小值?
- spss - 在SPSS中将包含日期的字符串变量转换为日期变量
- flutter - android.app.Application.ActivityLifecycleCallbacks 中定义的单元