根据现有内容制作多列

时间:2019-03-17 15:28:14

标签: python pandas

我目前有一列要分析的数据,然后将其放在其他列上。目前,我能得到的最好的结果就是使用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

但是通过申请,我能得到的最好的是

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

我可以使用apply 3次,但是读取整个数据集3次效率不高。

1 个答案:

答案 0 :(得分:1)

您应该通过比较数量|来更改函数,并通过三元运算符进行拆分,最后传递给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
相关问题