[英]How To transpose specific columns into rows in pandas associate other column value
[英]How to transpose specific columns in a dataframe and get counts for other columns in Pandas
我有一个这样的数据框
id a1 a2 a3 b1 b2
1 1 0 0 0 1
2 0 0 0 1 0
3 1 1 0 0 1
4 1 0 1 1 1
5 0 1 1 0 0
现在,我必须将以前缀“a”开头的列转换为行,并获取前缀为“b”的相应列的计数。 计数基本上是 'a' 和 'b' 在一个 id 中共同出现的次数。 共现仅当该 id 的两个值都为“1”时。
b1 b2
a1 1 3
a2 0 1
a3 1 1
在上面的示例中,a1,b2 对同时出现在 3 个 id(在 id 1,3 和 4)中,因此值为 3。
如何在 Pandas 中做到这一点?
矩阵乘法(使用 python 3.5+)
df[['a1', 'a2','a3']].T @ df[['b1','b2']]
更新:更普遍
df.filter(like='a').T @ df.filter(like='b')
或者
df.iloc[:,:3].T @ df.iloc[:,3:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.