Python 如何从多个数据帧中查找公共对/组
我几乎没有这样的数据帧Python 如何从多个数据帧中查找公共对/组,python,r,grouping,Python,R,Grouping,我几乎没有这样的数据帧 DF1 DF2 DF3 DF4 A 1 A 2 A 1 A 1 B 2 B 2 B 2 B 2 C 3 C 3 C 4 C 3 D 2 D 4 D 3 D 4 E 4 E 1 E 2 E 3 F 2 F 2 F 2 F 2 G 3
DF1 DF2 DF3 DF4
A 1 A 2 A 1 A 1
B 2 B 2 B 2 B 2
C 3 C 3 C 4 C 3
D 2 D 4 D 3 D 4
E 4 E 1 E 2 E 3
F 2 F 2 F 2 F 2
G 3 G 1 G 4 G 3
这里,数字表示组(具有相同数字的字母在同一组中)。就像在DF1中一样,(B,D,F)有2个,所以它们在同一组中
我想找出在所有数据帧中哪个组是可用的(比如(B,F)在所有数据帧中都在同一个组中。同样地,(C,G)在2个数据帧中都在同一个组中。
因此,我想知道哪个组(可能有2个以上的成员)在所有数据帧中都可用,如果它们在所有时间都不可用,它们在同一组中的次数是多少。最好是R和Python代码。这应该行得通,total列列出了特定字母在数据帧中出现的次数
df <- data.frame(grp = LETTERS[1:7],
df1 = c(1,2,3,2,4,2,3),
df2 = c(2,2,3,4,1,2,1),
df3 = c(1,2,4,3,2,2,4),
df4 = c(1,2,3,4,3,2,3))
# Create a new column which counts the maximum number of times the letter
# has the same group in each dataset.
df$total <- apply(df[, 2:ncol(df)], 1, function(row) max(table(row)))
grp df1 df2 df3 df4 total
1 A 1 2 1 1 3
2 B 2 2 2 2 4
3 C 3 3 4 3 3
4 D 2 4 3 4 2
5 E 4 1 2 3 1
6 F 2 2 2 2 4
7 G 3 1 4 3 2
# Show the rows for which the letters are present in the same group
# across all datasets.
df[df$total == ncol(df)-2,]
grp df1 df2 df3 df4 total
2 B 2 2 2 2 4
6 F 2 2 2 2 4
df您尝试过什么代码?在我看来,setdiff
,lappy
/%in%
,甚至table
都应该能给您一些有用的东西。