python - 使用 pandas 取消嵌套数组列

标签 python pandas

我的同事给了我一个数据集,其中包含带有嵌套数据的列:

id | ... | x
 0 | ... | [['a',3.0],['b',5.4]]
 1 | ... | [['a',1.3],['b',7.6]]
 2 | ... | [['b',2.4],['a',8.8]]
 : | ... | :                   :

我正在尝试将列解析为多个列以获得如下内容:

id | ... | a   | b
 0 | ... | 3.0 | 5.4
 1 | ... | 1.3 | 7.6
 2 | ... | 8.8 | 2.4
 : | ... | :   | :

不幸的是,我似乎无法找到使用 pandas 执行此操作的方法。我知道不鼓励以这种方式嵌套数据,但不幸的是我的同事并不认为这是一个问题,所以这就是我度过周末的方式。

有人有处理此类问题的经验吗?

最佳答案

我认为这应该有效:

records = [ dict(row) for row in df['x'].values ]
new_df = pd.DataFrame.from_records(records, columns = records[0].keys(), index = df.index)

(我没有测试它,所以可能需要一些更改)

关于python - 使用 pandas 取消嵌套数组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28663005/

相关文章:

python - 根据其他列和字典创建一个新列

python - ServiceNow JSON Web服务的Python身份验证

python - 使用elasticsearch_dsl(Python)时如何指定文档类型?同样,如何指定几个索引?

python - 使用 asyncio 协同程序进行方法链接

python - Pandas 中的字符串到日期时间格式

python - 如何在 Panda 的 from_dict (Python) 中使用 dtype 参数

python - Sphinx 不显示泛型类的类实例化参数(即参数类型)

python 守护进程 - 为什么这个函数会杀死父进程两次?

python - 选择存储在对象列中的日期时间的 DataFrame 行

python - Pandas:高效插入大量行