我有一个可以使用下面给出的代码创建的数据框
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']})
上面的代码生成如下所示的数据框
我想拆分数据框中每一行的内容并将它们作为单独的行
如何才能得到这样的输出?
最佳答案
使用Series.str.extractall
使用正则表达式获取带有文本点的整数值到 Series
,通过 reset_index
和 DataFrame.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
关于python - 分割数据帧的行并将它们作为单独的行存储在同一数据帧中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56536954/