python - 使用类的属性作为列的标题,从类的对象创建一个 DataFrame
问题描述
我有这个类项目,我很想将其转换为 DataFrame
projects = [(Project){
id = 21
UserDefinedFields = ""
ProjectName = "Connecting Python Script to AutoTask"
AccountID = 0
Type = 4
ExtPNumber = ""
ProjectNumber = "P20200311.0001"
Description = "This project is to test connection between a script and the CRM platform of AutoTask"
CreateDateTime = 2020-03-11 04:00:00+00:00
CreatorResourceID = 29684475
StartDateTime = 2020-03-11 04:00:00+00:00
EndDateTime = 2020-03-12 04:00:00+00:00
Status = 1
ProjectLeadResourceID = 29684475
CompletedPercentage = 0
StatusDetail = ""
StatusDateTime = 2020-03-11 15:34:50.310000+00:00
LastActivityResourceID = 29684475
LastActivityDateTime = 2020-03-11 15:34:50.433000+00:00
LastActivityPersonType = 1
}, (Project){
id = 22
UserDefinedFields = ""
ProjectName = "Larry and Brittany Test"
AccountID = 29683567
Type = 5
ExtPNumber = ""
ProjectNumber = "P20200311.0002"
Description = ""
CreateDateTime = 2020-03-11 04:00:00+00:00
CreatorResourceID = 29684474
StartDateTime = 2020-03-11 04:00:00+00:00
EndDateTime = 2020-03-12 04:00:00+00:00
Duration = 2
ActualHours = 0.0
ActualBilledHours = 0.0
EstimatedTime = 0.0
LaborEstimatedRevenue = 0.0
LaborEstimatedCosts = 0.0
LaborEstimatedMarginPercentage = 0.0
ProjectCostsRevenue = 0.0
ProjectCostsBudget = 0.0
ProjectCostEstimatedMarginPercentage = 0.0
ChangeOrdersRevenue = 0.0
SGDA = 0.0
OriginalEstimatedRevenue = 0.0
EstimatedSalesCost = 0.0
Status = 1
ProjectLeadResourceID = 29684474
CompletedPercentage = 0
StatusDetail = ""
StatusDateTime = 2020-03-11 22:08:22.267000+00:00
PurchaseOrderNumber = ""
LastActivityResourceID = 29684474
LastActivityDateTime = 2020-03-11 22:08:22.377000+00:00
LastActivityPersonType = 1
}]
id、UserDefinedFields、AccountID 都是类Project的属性
我想生产这样的数据框
id | UserDefinedFields | AccountID | ... |LastActivitityPersonType
21 | | 0 | ... |
22 | | 29683567 |.....| 1
对于没有属性值的对象,数据框应该添加一个空字符串
解决方案
- 不修改类:
pd.DataFrame([
{
k: v
for k, v
in project.__dict__.items()
if not callable(v)
}
for project in projects
])
- 添加 to_dict 方法并使用
from_records
class Project
def to_dict(self):
return {
attr: getattr(self, attr, '')
for attr in ['id', 'UserDefinedFields' .... ]
}
...
pd.Dataframe.from_records(projects)
推荐阅读
- r - UseMethod(“html_table”)中的错误:没有适用于“html_table”的方法应用于“NULL”类的对象
- flutter - 如何在 Flutter 中解码 GS1-128 条码中的 FNC1 码?
- python - 使用来自不同文件pygame的精灵对象类
- reactjs - Reducer 调度 React Redux
- azure - Azure 自定义标记策略,排除资源类型
- node.js - 无法访问 COVID 数据
- python - 如何使用 pygame.time.get_ticks() 在不影响用户输入的情况下进行延迟
- angular - 未找到模块:错误:无法解析“@firebase/app”Ionic Firebase
- regex - 如何在两个静态键之间提取字符串?
- python - 如何将 pip 与不同的 python 版本一起使用?