string - 将字符串拆分为熊猫中的列
问题描述
我有一个例子如下:
Name ID Score
A 1 Math: 80.0 Physical Education: 30.5 Biology: 50.0
B 2 Math: 70.0 Physical Education: 60.5 Biology: 50.0 English
Literature: 100.0
C 3 Math: 30.0 Physical Education: 10.5 Biology: 50.0
如何将“分数”列转换为列和整个数据框,如:
Name Subject Score
A Math 80.0
A Physical Education 30.5
A Biology 50.0
解决方案
尝试:
x = df[["Name", "ID"]].merge(
df["Score"]
.str.extractall(r"(?P<Subject>[^:]+)\s*:\s*(?P<Score>[\d.]+)")
.droplevel(1),
left_index=True,
right_index=True,
)
print(x)
印刷:
Name ID Subject Score
0 A 1 Math 80.0
0 A 1 Physical Education 30.5
0 A 1 Biology 50.0
1 B 2 Math 70.0
1 B 2 Physical Education 60.5
1 B 2 Biology 50.0
1 B 2 English Literature 100.0
2 C 3 Math 30.0
2 C 3 Physical Education 10.5
2 C 3 Biology 50.0
推荐阅读
- python - 使用 Accurate Scheduler 模拟时间序列事件
- java - 具有水平滚动标题的 HeaderListView
- pinterest - 使用 Pinterest Marketing api 获取所有实体?
- java - BigInt 对象的“add”方法异常
- r - 长格式的时间序列数据,合并特定行时间点,同时忽略每个参与者的其他时间点
- python - Visual Studio Code 无法正确引用虚拟环境中的包
- ads - 在华为快应用上请求原生广告时出现“字符串错误”
- google-apps-script - 使用脚本在 Google 表格中发送一张表格不起作用
- python - 使用 keras 进行 RNN 的三元组网络
- flutter - Flutter / Dart:StatefulWidget - 访问Widget内部的类变量