如何在 pandas 中计算每列中唯一项的出现次数?

How can I count occurrences of unique items per column across columns in pandas?

提问人:Sudoh 提问时间:9/15/2022 最后编辑:Sudoh 更新时间:9/15/2022 访问量:148

问:

假设我有一个如下所示:dataframe

指数
第一 一个 B C
第二 C 一个 B
第三 B 一个 C

我想要的是跨列的计数。df.iloc[:,1:]:

项目
一个 1 2 0
B 1 1 1
C 1 0 2

对第二个表计数的解释在每个计数旁边的括号中。

项目
一个 1(第 1 栏中只有一个 A) 2(第 2 列中 A 的两次计数) 0(第 3 栏中没有 A)
B 1(第1栏中只有一个B) 1(第 2 栏中只有一个 B) 1(第3栏为1 B)
C 1(第 1 列中只有一个 C) 0(第 2 列中没有 C) 2(第 3 列中 C 的两次计数)

我尝试了以下不太有效的方法:

  • df3.iloc[:,1:].value_counts().to_frame('counts').reset_index()

  • df[df.columns[1:]].value_counts()

上面两个单行线很接近,但还不完全存在。

我能想到的 Macgyvered 解决方案是逐一遍历列并对每个列进行操作并尝试组织计数,但鉴于每个列的顺序有些不同,这有点混乱。.value_counts().value_count

我应该怎么做?

python-3.x 熊猫

评论

0赞 Golden Lion 9/15/2022
为什么 B 的第一列 2 是值 2?我没有看到模式
0赞 Sudoh 9/15/2022
因为第二列中有 2 个 A 计数,B 有 1 个计数(在第二列中),C 有 0 个计数(在第二列中)。跨列计算每列的项目数。

答:

2赞 Echo 9/15/2022 #1

试试这个:

df = df.apply(pd.value_counts).fillna(0)

哎呀,它有帮助。

评论

0赞 Sudoh 9/15/2022
是否确定?我得到.TypeError: unhashable type: 'list'
1赞 Echo 9/15/2022
是的,非常确定,因为我复制粘贴了您的确切 DataFrame 并得到了您正在寻找的确切输出。可能 DataFrame 中的实际数据并不像您的问题中那么简单,您是否在 DataFrame 的某个地方有一个列表作为值或 sth?
1赞 Sudoh 9/15/2022
你是对的,我在那里有几个清单。
2赞 Timeless 9/15/2022 #2

试试这个:

from io import StringIO
import pandas as pd

s = """Index    one two three
First   A   B   C
Second  C   A   B
Third   B   A   C"""

df  = pd.read_csv(StringIO(s), sep='\t').set_index('Index')

df = (df.apply(pd.value_counts).fillna(0)
      .apply(pd.to_numeric,downcast='integer')
      .reset_index()
      .rename(columns={'index':'Item'})
     )
>>> display(df)

enter image description here

0赞 Golden Lion 9/15/2022 #3

在 Apply 中使用 value_counts for the DataFrame

data="""Index,one,two,three
First,A,B,C
Second,C,A,B
Third,B,A,C
"""
df = pd.read_csv(io.StringIO(data), sep=',')


df=df.apply(lambda x: x.value_counts()).fillna(0)
df=df.drop(labels=['First','Second','Third'],axis=0)

print(df)