Python 基于标签位置的熊猫数据帧索引计数
我试图在每列中计算Python 基于标签位置的熊猫数据帧索引计数,python,pandas,Python,Pandas,我试图在每列中计算DataFrame中标签的索引。基本上,我有以下DataFrame: d = {'col1': ['label1', 'label2', 'label3'], 'col2': ['label2', 'label3', 'label1'], 'col3': ['label2', 'label1', 'label3'], 'col4': ['label3', 'label1', 'label2']} df = pd.DataFrame(data
DataFrame
中标签的索引。基本上,我有以下DataFrame
:
d = {'col1': ['label1', 'label2', 'label3'],
'col2': ['label2', 'label3', 'label1'],
'col3': ['label2', 'label1', 'label3'],
'col4': ['label3', 'label1', 'label2']}
df = pd.DataFrame(data = d)
哪些格式为:
col1 col2 col3 col4
0 label1 label2 label2 label3
1 label2 label3 label1 label1
2 label3 label1 label3 label2
其思想是将所有列上每个标签的索引计数到一个数组(或数据帧)中,如下所示:
label1 label2 label3
0 1 2 1
1 2 1 1
2 1 1 2
这表明,例如,label1
在原始DataFrame
中的索引0处出现一次,在索引1处出现两次,在索引2处出现一次
我在一个循环中执行此操作,因此最好使用一种有效的方法。有什么想法吗?使用:
df = df.apply(pd.value_counts, axis=1)
print (df)
label1 label2 label3
0 1 2 1
1 2 1 1
2 1 1 2