拆分数据帧的行,并将其作为单独的行存储在同一数据帧中

时间:2019-06-11 05:20:16

标签: python regex python-3.x pandas dataframe

我有一个数据框,可以使用下面给出的代码创建

df = pd.DataFrame({'Person_id':[1,2,3,4],
'Values':['father:1.Yes 2.No 3.Do not Know','Mother:1.Yes 777.No 999.Do not 
Know','sons:1.Yes 2.No 321.Do not Know','daughter:1.Yes 567.No 3.Do not Know'],
'Ethnicity':['dffather','dfmother','dfson','dfdaughter']})

上面的代码产生一个如下所示的数据帧

enter image description here

我想将数据帧中每一行的内容拆分为单独的行

如何获得这样的输出?

enter image description here

1 个答案:

答案 0 :(得分:2)

使用Series.str.extractall和正则表达式获取带有指向Series的文本的整数值,将reset_indexDataFrame.join的第二级删除为原始值,必要时最后设置重复的值用Series.duplicated来清空字符串:

cols = df.columns
s = (df.pop('Values')
       .str.extractall('(\d+\.\D+)')[0]
       .str.strip()
       .reset_index(level=1, drop=True)
       .rename('Values'))

df = df.join(s).reindex(cols, axis=1).reset_index(drop=True)
df.loc[df['Person_id'].duplicated(), 'Ethnicity'] = ''
print (df)
    Person_id           Values   Ethnicity
0           1            1.Yes    dffather
1           1             2.No            
2           1    3.Do not Know            
3           2            1.Yes    dfmother
4           2           777.No            
5           2  999.Do not Know            
6           3            1.Yes       dfson
7           3             2.No            
8           3  321.Do not Know            
9           4            1.Yes  dfdaughter
10          4           567.No            
11          4    3.Do not Know