基于现有列创建多个列

2024-06-10 08:57:16 发布

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

我当前有一个列,其中包含我要分析的数据,然后将这些数据放在其他列上。目前,我能得到的最好结果是使用apply方法:

def parse_parent_names(row):
    split = row.person_with_parent_names.split('|')[2:-1]
    return split

df['parsed'] = train_data.apply(parse_parent_names, axis=1).head()

数据是一个熊猫df,其列的名称由管道(|)分隔:

'person_with_parent_names'
|John|Doe|Bobba|
|Fett|Bobba|
|Abe|Bea|Cosby|

最右边的是人,最左边的是“最伟大的父母”。我想将其转换为三列,如:

'grandfather'    'father'    'person'
John             Doe         Bobba
                 Fett        Bobba
Abe              Bea         Cosby

但有了apply,我能得到的最好结果就是

'parsed'
[John, Doe,Bobba]
[Fett, Bobba]
[Abe, Bea, Cosby]

我可以使用apply三次,但是三次读取整个数据集是没有效率的


Tags: 数据namesparsejohnparentpersonrowsplit
1条回答
网友
1楼 · 发布于 2024-06-10 08:57:16

应通过比较|的数量来更改函数,并通过三元运算符拆分,最后传递给DataFrame构造函数:

def parse_parent_names(row):
    m = row.count('|') == 4
    split = row.split('|')[1:-1] if m else row.split('|')[:-1]
    return split

cols = ['grandfather','father','person']
df1 = pd.DataFrame([parse_parent_names(x) for x in df.person_with_parent_names],
                    columns=cols)
print (df1)
  grandfather father person
0        John    Doe  Bobba
1               Fett  Bobba
2         Abe    Bea  Cosby

相关问题 更多 >