首页 > 解决方案 > 拆分数据帧的行并将它们作为单独的行存储在同一数据帧中

问题描述

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

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']})

上面的代码生成如下所示的数据帧

在此处输入图像描述

我想拆分数据框中每一行的内容并将它们作为单独的行

我怎样才能得到这样的输出?

在此处输入图像描述

标签: pythonregexpython-3.xpandasdataframe

解决方案


与正则表达式一起使用Series.str.extractall以获取带有文本的整数值 to Series,删除第二级 byreset_indexDataFrame.jointo original ,最后如果有必要将重复值设置为空字符串 by 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            

推荐阅读