【发布时间】:2020-03-22 21:40:17
【问题描述】:
R 语言中的tidyr::unnest 方法在pandas 中是等效的,它被称为explode,如this very detailed answer 中所述。
我想知道是否有与 ̀tidyr::nest 方法等效的方法。
示例 R 代码:
library(tidyr)
iris_nested <- as_tibble(iris) %>% nest(data=-Species)
数据列是一个列表列,其中包含数据框(这对于建模很有用,例如在运行多个模型时)。
iris_nested
# A tibble: 3 x 2
Species data
<fct> <list<df[,4]>>
1 setosa [50 × 4]
2 versicolor [50 × 4]
3 virginica [50 × 4]
访问数据列中的一个元素:
iris_nested[1,'data'][[1]]
[...]
# A tibble: 50 x 4
Sepal.Length Sepal.Width Petal.Length Petal.Width
<dbl> <dbl> <dbl> <dbl>
1 5.1 3.5 1.4 0.2
2 4.9 3 1.4 0.2
3 4.7 3.2 1.3 0.2
4 4.6 3.1 1.5 0.2
5 5 3.6 1.4 0.2
6 5.4 3.9 1.7 0.4
7 4.6 3.4 1.4 0.3
8 5 3.4 1.5 0.2
9 4.4 2.9 1.4 0.2
10 4.9 3.1 1.5 0.1
# … with 40 more rows
library(tidyr)
iris_nested <- as_tibble(iris) %>% nest(data=-Species)
iris_nested
iris_nested[1,'data'][[1]]
示例python代码:
import seaborn
iris = seaborn.load_dataset("iris")
如何在 pandas 中嵌套这个数据框:
- 首先以一种不太复杂的方式(与pandas explode 功能相比)数据列包含一个简单列表
- 其次,数据列包含如上例所示的数据帧
【问题讨论】: