透视逆透视:R语言(reshape2tidyverse),Excel,Python

Posted 基督徒Isaac

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了透视逆透视:R语言(reshape2tidyverse),Excel,Python相关的知识,希望对你有一定的参考价值。

  • 总结(Python的pandas,R语言的reshape2、tidyr)

  • R语言(reshape2、tidyverse)

数据来源:R语言实战第二版P106

library(tidyverse)
library(reshape2)

# 透视、逆透视
# R语言实战第二版P106
# https://r4ds.had.co.nz/
# https://bookdown.org/Maxine/r4ds/
# https://bookdown.org/Maxine/r4ds/pivoting.html

# sqldf     https://blog.csdn.net/yunru_yang/article/details/60749026
# reshape2  https://www.jianshu.com/p/36f5268e932c
# tidyr     https://www.jianshu.com/p/46a53717d964

# melt(融)变长pivot_longer(逆透)列名:组合新名
# dcast(拆)变宽pivot_wider(透视)列名:组内变量

# mydata <- cbind(ID, Time, X1, X2) %>% data.frame(); mydata
mydata <- readxl::read_excel("WPS Cloud Files/368440790/pivot.xlsx", sheet = "Sheet4"); mydata

# 变长
md <- mydata %>% melt(id.vars = c("ID","Time")); md
mydata %>% pivot_longer(cols = c("X1","X2"), names_to = "variable") %>% arrange(variable)

# 变宽
md %>% dcast(ID+Time~variable, value.var = "value")
md %>% pivot_wider(id_cols = c(ID, Time), names_from = variable, values_from = value)

# 变宽(汇总依据 = mean)
md %>% dcast(ID~variable, value.var = "value", fun.aggregate = mean)
md %>% pivot_wider(id_cols = ID, names_from = variable, values_from = value, values_fn = mean)
  • Python
# pivot 初级重组
# pivot_table 数值处理
# melt 逆透变长

# 导入Excel https://zhuanlan.zhihu.com/p/88653839
# 透视表 https://blog.csdn.net/weixin_31669073/article/details/112217335
# https://blog.csdn.net/AaronPaul/article/details/106682486
# https://blog.csdn.net/shine4869/article/details/105635203
# https://www.cnblogs.com/zlslch/p/8644585.html
# https://zhuanlan.zhihu.com/p/54066705
# https://pandas.pydata.org/pandas-docs/stable/index.html
from pandas import *

mydata = read_excel("e:pivot.xlsx", sheet_name = "Sheet4") # header, name, index_col
mydata

md = mydata.melt(id_vars = ["ID", "Time"],
                 value_vars = ["X1", "X2"],
                 var_name = "variable",
                 value_name = "value"); md

md.pivot(index = ["ID", "Time"],
         columns = "variable",
         values = "value")

md.pivot_table(index = ["ID", "Time"],
               columns = "variable",
               values = "value")

md.pivot_table(index = ["ID"],
               columns = "variable",
               values = "value",
               aggfunc = ["mean","sum"])
  • Excel数据透视表的组合分段方法:

  • SQL

https://www.jianshu.com/p/afad4da7d5a8

以上是关于透视逆透视:R语言(reshape2tidyverse),Excel,Python的主要内容,如果未能解决你的问题,请参考以下文章

图像透视基于matlab图像逆透视映射含Matlab源码 2139期

图像透视基于matlab图像逆透视映射含Matlab源码 2139期

Oracle 逆透视分组

《MSSQL2008技术内幕:T-SQL语言基础》读书笔记(下)

《MSSQL2008技术内幕:T-SQL语言基础》读书笔记(下)

世界空间逆投影透视