【问题标题】:How to count the occurrence of different versions of a string in a column of a Python dataframe?如何计算 Python 数据框列中不同版本字符串的出现次数?
【发布时间】:2017-11-11 10:24:23
【问题描述】:

我有一个数据框。 Click here to get the pic of the dataframe:

换句话说:

MALE/M/male/Male 表示男性。

Female,F,Fem 表示女性。

YES/yes/yeah 表示正面回答。

否定回答用 no/NO/nope 表示。

所以,对于上述数据框,我想在 Python 中计数,男性的总数,女性的总数total 正面回应的数量和 total 负面回应的数量。我该怎么做?

【问题讨论】:

  • 您可以使用 df.to_clipboard() 获取数据帧的样本,它比图像更能帮助人们掌握您的数据。

标签: python pandas dataframe count


【解决方案1】:

您需要str[0] 选择每列的第一个字母,转换为lower,通过sum 比较和计算Trues 的数量:

df = pd.DataFrame(data={'Gender':['Male', 'MALE', 'Female', 'F', 'M'],
                        'Response': ['yes', 'N', 'no', 'nope', 'NO']})
print (df)
   Gender Response
0    Male      yes
1    MALE        N
2  Female       no
3       F     nope
4       M       NO

count = len(df.index)
males = (df['Gender'].str[0].str.lower() == 'm').sum()
females = (df['Gender'].str[0].str.lower() == 'f').sum()

yes = (df['Response'].str[0].str.lower() == 'y').sum()
no = (df['Response'].str[0].str.lower() == 'n').sum()

print (count)
5
print (males)
3
print (females)
2
print (yes)
1
print (no)
4

另一个解决方案是value_counts,然后是concat,最后用dict重命名index值:

a = df['Gender'].str[0].str.lower().value_counts()
b = df['Response'].str[0].str.lower().value_counts()

s = pd.concat([a,b])
s.loc['count'] = len(df.index)
d = {'m':'male', 'f':'female', 'y':'yes', 'n':'no'}
s = s.rename(index=d)
print (s)
male      3
female    2
no        4
yes       1
count     5
dtype: int64

【讨论】:

    【解决方案2】:

    首先你可以得到每个值的计数:

    df.Gender.count_values()
    

    然后添加你想要组合在一起的值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 2019-08-14
      • 1970-01-01
      相关资源
      最近更新 更多