Python 计算与另一列对应的列中非零的数量
我有一个数据帧:Python 计算与另一列对应的列中非零的数量,python,pandas,Python,Pandas,我有一个数据帧: d = {'class': [0, 1,1,0,1,0], 'A': [0,4,8,1,0,0],'B':[4,1,0,0,3,1]} df = pd.DataFrame(data=d) 看起来像- A B class 0 0 4 0 1 4 1 1 2 8 0 1 3 1 0 0 4 0 3 1 5 0 1 0 我想计算每个列对应的a、b、c、d,它们在类列1对应的列中不为零,在类
d = {'class': [0, 1,1,0,1,0], 'A': [0,4,8,1,0,0],'B':[4,1,0,0,3,1]}
df = pd.DataFrame(data=d)
看起来像-
A B class
0 0 4 0
1 4 1 1
2 8 0 1
3 1 0 0
4 0 3 1
5 0 1 0
我想计算每个列对应的a、b、c、d,它们在类列1对应的列中不为零,在类列0对应的列中不为零,在类列1对应的列中不为零,在类列0对应的列中不为零 比如说-
for column A the a,b,c,d are 2,1,1,2
解释-在A列中,我们看到当列[class]=1时,A列中非零值的数量为2,因此A=2表示1,2。类似地,b=1表示3
当数据帧的0和1类的编号相等时,我的尝试-
dataset = pd.read_csv('aaf.csv')
n=len(dataset.columns) #no of columns
X=dataset.iloc[:,1:n].values
l=len(X) #no or rows
score = []
for i in range(n-1):
#print(i)
X_column=X[:,i]
neg_array,pos_array=np.hsplit(X_column,2)##hardcoded
#print(pos_array.size)
a=np.count_nonzero(pos_array)
b=np.count_nonzero(neg_array)
c= l/2-a
d= l/2-b
使用:
我想计算每列的值a,b,c,d@ubuntu_noob-它计算所有没有类的列,对你来说它不起作用?它只计算a和b,我想计算a,b,c,d@ubuntu_noob-是的,只计算A和B,因为样本中的数据不是c和d列。colB的答案是2,2,1,1…是否可能是c,d的互换?
d = {'class': [0, 1,1,0,1,0], 'A': [0,4,8,1,0,0],'B':[4,1,0,0,3,1]}
df = pd.DataFrame(data=d)
df = (df.set_index('class')
.ne(0)
.stack()
.groupby(level=[0,1])
.value_counts()
.unstack(1)
.sort_index(level=1, ascending=False)
.T)
print (df)
class 1 0 1 0
True True False False
A 2 1 1 2
B 2 2 1 1
df.columns = list('abcd')
print (df)
a b c d
A 2 1 1 2
B 2 2 1 1