python - 分割数据帧的行并将它们作为单独的行存储在同一数据帧中

标签 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

最佳答案

使用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            

关于python - 分割数据帧的行并将它们作为单独的行存储在同一数据帧中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56536954/

相关文章:

python - 让子类有自己的类属性

javascript - 如何验证 Angular 国家/地区的手机号码?

python-3.x - PYTHON - 删除 cosmos db 分区集合中的文档

python - 无法将列表保存到 Google App Engine 上的 db.ListProperty()

python - 如何 pip 安装具有最小和最大版本范围的软件包?

python - 使用 SQLite 作为键 :value store

java - 删除所有非数字字符但保留特定单词

regex - Vim - 使用正则表达式按字典顺序比较字符串(以查找更早/更晚的日期)

caching - python 3 suds 缓存不工作

python - 数据不会在文档中解析,但会在 Python 中解析为虚拟数据