python - 拆分数据帧的行并将它们作为单独的行存储在同一数据帧中
问题描述
我有一个可以使用下面给出的代码创建的数据框
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
以获取带有文本的整数值 to Series
,删除第二级 byreset_index
和DataFrame.join
to 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
推荐阅读
- java - List vs LinkedList vs ArrayList
- elasticsearch - 如何进行嵌套术语查询
- javascript - 缩小粘性粘性标题会导致 Blink/Webkit 在某些滚动位置闪烁
- asp.net - 为什么部署中只有一部分 pod 启动成功?
- r - 如何在 R 中一次命名多个列表中的对象?
- go - Golang 服务器发送事件 - 服务器发送事件处理程序是否不断调用自己?
- microsoft-graph-api - 通过 Microsoft Graph SDK 更新时,架构扩展值始终为 NULL
- javascript - 如何在 React Native 中共享容器截图 | 安卓博览会
- javascript - addEventListener 回调中的错误处理
- jquery-select2 - select2 多个选项,对用户输入没有自动排序并保留所选顺序