如何计算列中每种类型的标签并将其保存在变量中?

2024-05-18 14:50:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须计算数据帧列中出现1和0的时间数。我尝试了以下代码:

count_own_party = len(df['Deviation from Partisanship']== 1)
count_opposing_party = len(df['Deviation from Partisanship'] == 0)

print(count_own_party)
print(count_opposing_party)

这两个值的输出相同:7854。虽然从graph可以清楚地看到1的数量大于0的数量


Tags: 数据代码fromdf数量lenpartycount
1条回答
网友
1楼 · 发布于 2024-05-18 14:50:38

为此,熊猫中有一个功能: ^{}

value_count=df['Deviation from Partisanship'].value_counts()
count_0=value_count[0]
#count_0=value_count['0'] # if it is str
count_1=value_count[1]
#count_1=value_count['1'] # if it is str

以下是一个例子:

print(df)
    Mnth  Income
0    Jan      80
1    Feb      80
2    Mar      50
3  April      60
4    May      60

value_count=df['Income'].value_counts()
print(value_count)



60    2
80    2
50    1
Name: Income, dtype: int64

count_60 = value_count[60]
print(count_60)
#2

相关问题 更多 >

    热门问题