在pandas中,如何将一个具有许多属性和值的列解析为新的列并获取它们的值

2024-09-30 06:30:05 发布

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

我有一个由许多列组成的数据帧,其中一个列名为SourceTechAttributes,它具有有价值的attributeName和属性值,例如

    df['SourceTechAttributes'][0]
    'DropFrame: True, Duration: 4874.1359333333333333333333333, FieldDominance: Upper Field First, FrameRate: 29.97, Height: 1080, MediaFormat: 912, NumberOfAudioChannels: 8, NumberOfAudioTracks: 8, ScanType: Interlaced, StartSmpte: 00:59:59;26, ViewportDisplayFormat: Anamorphic, Width: 1920'
0    DropFrame: True, Duration: 4874.13593333333333...
1    ActionType: CG, DropFrame: True, Duration: 129...
2    DropFrame: True, Duration: 4874.13593333333333...
3    DropFrame: True, Duration: 4874.13593333333333...
4    ActionType: CG, DropFrame: True, Duration: 129...
5    ActionType: CG, DropFrame: True, Duration: 129...
Name: SourceTechAttributes, dtype: object

此列键和值也会更改其位置, 我想解析该列并创建新的七列,如下所示 enter image description here

我可以在熊猫身上一个接一个像

^{pr2}$

其中的第一个结果是逗号

^{3}$

然后再次解析冒号分隔,取最后一部分并将列名指定为df['DropFrame']

df['DropFrame']=df['m'][0].split(':')[1]
df['DropFrame']

0         True
1         True
2         True
3         True

但是这个过程给出了错误的结果,因为有时它没有得到我想要的结果,因为一些行的属性和值很多,有时很少。有谁能在这件事上帮助我,创造一个功能,将照顾所有这些,我可以实现我的目标。提前谢谢。在


Tags: 数据truefielddf属性uppercgfirst
2条回答

以下3个步骤:

# 1. create a list in each row
df['SourceTechAttributes'] = (df['SourceTechAttributes']
                              .apply(lambda x: str(x).replace(" ", "")
                                     .replace(":", ",")
                                     .split(",")))

# 2. create a dictionary in each row
df['SourceTechAttributes'] = (df['SourceTechAttributes']
                              .apply(lambda x: dict(zip(x[::2], x[1::2]))))

# 3. create new columns
df['srcMediaFormat'] = (df['SourceTechAttributes']
                        .apply(lambda x: x['MediaFormat']))

我只创建了一个新列srcMediaFormat作为示例。在

首先,您需要一个函数,它接受一个字符串,然后用逗号和冒号将其拆分,然后通过字典将其转换为pandas系列:

def str2series(s):
    pieces = [x.split(': ') for x in s.split(',')]
    return pd.Series({k.strip(): v.strip() for k,v in pieces})

接下来,将函数应用于列:

^{pr2}$

结果是您要查找的数据帧。如果需要,可以将其与原始数据帧合并:它们具有相同的索引:

df = df.join(new_df)

相关问题 更多 >

    热门问题