看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)以下有一个列表嵌套字典 data,列表中的每个字典 fields 中的列表为每行数据的值,另有一个 col 为列名,利用这两个数据构造一个 DataFrame。
data = [
{'fields': ['2024-10-07T21:22:01', 'USER-A', 21, 0, 0, 21]},
{'fields': ['2024-10-07T21:18:28', 'USER-B', 20, 20, 0, 45]}
]
cols = ['Created On', 'Created By', 'Transaction Count (ALL)',
'X Pending', 'X Cancelled (X)', 'X Completed (Y)']
以下为 Python 代码:
import pandas as pd
data = [
{'fields': ['2024-10-07T21:22:01', 'USER-A', 21, 0, 0, 21]},
{'fields': ['2024-10-07T21:18:28', 'USER-B', 20, 20, 0, 45]}
]
cols = ['Created On', 'Created By', 'Transaction Count (ALL)',
'X Pending', 'X Cancelled (X)', 'X Completed (Y)']
# 构造代码
(
pd.DataFrame(data)
.fields
.apply(pd.Series)
.set_axis(cols, axis=1)
)
输出:
'''
Created On Created By ... X Cancelled (X) X Completed (Y)
0 2024-10-07T21:22:01 USER-A ... 0 21
1 2024-10-07T21:18:28 USER-B ... 0 45
'''
查看相关链接中的知识。
(完)
更新时间:2025-02-03 09:53:56 标签:pandas python dataframe