pandas - 爆炸具有字典列表的数据框中的 1 列,每个字典应该是一个新列
问题描述
我有一个数据框,其中有一列如下所示:
附件.数据 | 标题 2 |
---|---|
[{'title': '测试标题', 'unshimmed_url': 'https://www.etc.com'}] | 34 |
[{'title': 'This is another Test Title for Testing', 'unshimmed_url': 'https://www.etc2.com'}] | 42 |
并想分开title
并使其成为新的列名并链接unshimmed_url
我已经尝试过了,但我认为我错过了一个步骤,因为我丢失了标题 2 和标题 3 列,现在它只是名称和链接列..
s = df['attachments.data'].explode()
calcu = pd.DataFrame(s.tolist(), index=s.index)
df2 = calcu.rename(columns={'title': 'name', 'unshimmed_url': 'link'})
解决方案
pop
,attachments.data
以相同的方式创建 DataFrame,但随后join
返回df
:
s = df.pop('attachments.data').explode()
df = df.join(
pd.DataFrame(s.tolist(), index=s.index)
.rename(columns={'title': 'name', 'unshimmed_url': 'link'})
)
df
:
Heading 2 name link
0 34 Test Title for Testing https://www.etc.com
1 42 This is another Test Title for Testing https://www.etc2.com
或者不修改df
drop
并创建一个新的DataFrame:
s = df['attachments.data'].explode()
df2 = df.drop(columns='attachments.data').join(
pd.DataFrame(s.tolist(), index=s.index)
.rename(columns={'title': 'name', 'unshimmed_url': 'link'})
)
或者构建新列:apply
pd.Series
df2 = df.drop(columns='attachments.data').join(
df['attachments.data'].explode()
.apply(pd.Series)
.rename(columns={'title': 'name', 'unshimmed_url': 'link'})
)
df2
:
Heading 2 name link
0 34 Test Title for Testing https://www.etc.com
1 42 This is another Test Title for Testing https://www.etc2.com
数据框和导入:
import pandas as pd
df = pd.DataFrame({
'attachments.data': [
[{'title': 'Test Title for Testing',
'unshimmed_url': 'https://www.etc.com'}],
[{'title': 'This is another Test Title for Testing',
'unshimmed_url': 'https://www.etc2.com'}]],
'Heading 2': [34, 42]
})
推荐阅读
- c# - 从c#调用contentplaceholder中的js函数-asp中的代码不起作用
- reactjs - 如何格式化这个 gatsby-config.js 文件以便为画布模块创建一个虚拟节点?
- javascript - JS、内联 CSS 和 getBoundingClientRect 之间的 style.top 不一致
- authentication - 如何将用户引导到登录页面而不是 Flask HTTPBasicAuth 中的登录弹出窗口?
- collections - Hyperledger 私有数据收集和保密性
- javascript - 如何在反应组件或无默认 URL 中插入 facebook like 按钮
- python - 将成对距离的长格式数据帧转换为python中的距离矩阵
- python - 在 vscode 中使用 ctrl+click 打开时,在 django 模块中看不到代码(每个函数和类块显示 3 个点)
- reactjs - Redux 不会更新状态
- android - 当我在实现设备中运行应用程序并用户单击图像时,我会质疑,它会崩溃。但它不能在模拟器中崩溃