pandas使用之宽表变窄表的实现
作者:爾莎 时间:2022-04-21 06:04:02
我就废话不多说了,还是直接看代码吧!
import pandas as pd
# 伪造一些数据
fake_data = {'subject':['math', 'english'],
'A': [88, 90],
'B': [70, 80],
'C': [60, 78]}
# 宽表
test = pd.DataFrame(fake_data, columns=['subject', 'A', 'B', 'C'])
test
subjectABC
0math887060
1english908078
# 转换为窄表
pd.melt(test, id_vars=['subject'])
subjectvariablevalue
0mathA88
1englishA90
2mathB70
3englishB80
4mathC60
5englishC78
补充知识:pandas从单条目数据集生成宽表
需求
场景
从医院数据库中导出了大量的体检数据,但体检数据表中,每一行代表某人某次体检的某一项体检的结果。目的想将每一个人的每一次体检结果作为一行存储,每一列为体检项。
示例
StuID | Type | Num | |
---|---|---|---|
0 | 111021 | Math | 89 |
1 | 111021 | English | 93 |
2 | 312983 | English | 91 |
3 | 314621 | English | 82 |
4 | 314621 | Math | 92 |
5 | 112341 | Math | 82 |
目的:转换成如下表格
StuID | English | Math | |
---|---|---|---|
0 | 111021 | 93 | 89 |
1 | 312983 | 91 | NaN |
2 | 314621 | 82 | 92 |
3 | 112341 | NaN | 82 |
方案一
具体代码如下
#将'B'列的类别调整为行。
#1
num = df[~df.duplicated(subset=['StuID'])].loc[:,'StuID'].to_list()
#2
result_df = pd.DataFrame({'StuID': np.array(num)},columns=['StuID','English','Math'])
#3
for i in df.index:
t = df.loc[i,'Type']
num = df.loc[i,'StuID']
result_df.loc[result_df['StuID'] == num,[t]] = df.loc[i,'Num']
print(result_df)
结果
来源:https://blog.csdn.net/Guo_ya_nan/article/details/82955345
标签:pandas,宽表,窄表
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django web自定义通用权限控制实现方法
2021-07-31 06:21:09
解决python虚拟环境切换无效的问题
2023-02-01 14:37:50
![](https://img.aspxhome.com/file/2023/0/77860_0s.jpg)
PYTHON基础-时间日期处理小结
2023-04-23 02:02:59
selenium 多窗口切换的实现(windows)
2021-08-17 03:58:54
iframe高度自适应,兼容IE,FF
2008-06-18 12:15:00
django模板结构优化的方法
2023-11-12 11:57:02
在Python的Flask框架中构建Web表单的教程
2023-10-04 06:03:12
![](https://img.aspxhome.com/file/2023/5/90745_0s.png)
python 文件操作删除某行的实例
2022-09-21 12:15:18
Python数据结构之链表详解
2023-07-21 04:16:19
![](https://img.aspxhome.com/file/2023/6/80796_0s.png)
SQL Server 2005如何设置多字段做关键字
2009-01-08 15:57:00
pytest解读一次请求多个fixtures及多次请求
2023-07-20 01:13:43
python 判断自定义对象类型
2021-08-29 22:09:37
Python unittest装饰器实现原理及代码
2022-05-06 22:33:49
通过SQL Server的位运算功能巧妙解决多选查询方法
2012-01-29 17:54:35
Sql Server表死锁的解决方法分享
2011-09-01 19:08:00
python爬虫可以爬什么
2022-05-26 01:24:31
javascript preload&lazy load
2023-09-01 06:15:43
详解Python中的相对导入和绝对导入
2023-02-05 01:10:36
sqlserver 多表查询不同数据库服务器上的表
2012-04-13 11:41:51
mysql myisam优化设置
2010-03-13 16:59:00