如何检查数据框是否包含列表或字典

时间:2020-03-30 08:56:52

标签: python-3.x pandas list dataframe dictionary

我有一个数据框:

col1   col2   col3       col4   
A     11    [{'id':2}]    {"price": 0.0}
B     21    [{'id':3}]    {"price": 2.0}
C     31    [{'id':4}]    {"price": 3.0}

我想找出所有列的数据类型为“列表”和“字典”,然后将结果存储到另一个列表中。 我该怎么办?

当我使用这个: data.applymap(type).apply(pd.value_counts) 输出是:

col1  col2        col3            col4
0    a    11  [{'id':2}]  {"price": 0.0}
1    b    21  [{'id':3}]  {"price": 2.0}
2    c    31  [{'id':4}]  {"price": 3.0}

1 个答案:

答案 0 :(得分:2)

IIUC,

我们可以使用ast标准库中的classes <- c("F", "G", "M", "O") classes <- structure(unique(classes), names = unique(classes)) S1 = data.frame(X1 = rnorm(100), X2 = rnorm(100), X3 = rnorm(100), X4 = rep(classes, 25)) S2 = data.frame(X1 = rnorm(100), X2 = rnorm(100), X3 = rnorm(100), X4 = rep(classes, 25)) P <- lapply(classes, function(c){ Output1 <- list ("model" = lm(X3~ X1+X2, data = S1),"mean" = apply(S1[S1$X4 == c, 1:3], 2, mean), "sum" = apply(S1[S1$X4 == c, 1:3], 2, sum)) Output2 <- list ("model" = lm(X3~ X1+X2, data = S2), "mean" = apply(S2[S2$X4 == c, 1:3], 2, mean), "sum" = apply(S2[S2$X4 == c, 1:3], 2, sum)) output <- list ("Output1" = Output1, "Output2" = Output2) return(output) }) classes <- c("F", "G", "M", "O") classes <- structure(unique(classes), names = unique(classes)) S1 = data.frame( X1 = rnorm(100), X2 = rnorm(100), X3 = rnorm(100), X4 = rep(classes, 25), ts = seq(from = ISOdate(1910,1,1), by = "30 min", length.out = 100 )) S2 = data.frame( X1 = rnorm(100), X2 = rnorm(100), X3 = rnorm(100), X4 = rep(classes, 25),ts = seq(from = ISOdate(1910,1,1), by = "30 min", length.out = 100 )) P <- lapply(classes, function(c){ Output1 <- list ("model" = lm(X3~ X1+X2, data = S1),"mean" = data.frame(ts = S1[S1$X4 == c, "ts"], value = S1[S1$X4 == c, "X1"]) , "sum" = apply(S1[S1$X4 == c, 1:3], 2, sum)) Output2 <- list ("model" = lm(X3~ X1+X2, data = S2), "mean" = data.frame(ts = S2[S2$X4 == c, "ts"], value = S2[S2$X4 == c, "X1"]), "sum" = apply(S2[S2$X4 == c, 1:3], 2, sum)) output <- list ("Output1" = Output1, "Output2" = Output2) return(output) }) 来建立字典:

出于性能原因,由于apply的计算量很大,因此让我们使用数据帧的第一行。

literal_eval

apply