如何在python中将数据帧中的列转换为嵌套字典?

2024-04-29 13:43:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列,上面有命名的工作记录,如下所示:

^{tb1}$

我想为这个专栏找到一个结构,这样当我尝试在一系列日期(比如从2021年9月1日到2021年9月30日)上进行汇总时,它会给出每个名字花费的总小时数

我尝试将列更改为列表,然后更改为字典,但它不起作用

如何在python中更改此列结构?我应该用正则表达式吗

{18/9/2021 : {Aya:20}, 20/9/2021 : {Asmaa:10}, 20/9/2021 : {Aya:20} }


Tags: 列表字典记录名字结构命名汇总花费
1条回答
网友
1楼 · 发布于 2024-04-29 13:43:28

您可以在这里使用dict,但它必须嵌套,因为每个日期都有多个条目

import pandas as pd
df = pd.DataFrame({'Records': ['Name: hours on date, Name: hours on date',
  'Aya: 20 on 18/9/2021, Asmaa: 10 on 20/9/2021, Aya: 20 on 20/9/2021']})

# Keep only rows that have the actual data
data = df.loc[~df['Records'].str.contains('Name')]

# Split on the comma delimiter and explode into a unique row per employee
data = data['Records'].str.split(',').explode()

# Use regex to capture the relevant data and construct the dictionary
data = data.str.extract('([a-zA-z]+)\:\s(\d{1,2})\son\s(\d{1,2}\/\d{1,2}\/\d{4})').reset_index(drop=True)

data.groupby(2).apply(lambda x: dict(zip(x[0],x[1]))).to_dict()

输出

{'18/9/2021': {'Aya': '20'}, '20/9/2021': {'Asmaa': '10', 'Aya': '20'}}

相关问题 更多 >