是否有 python 函数来 运行 计数,其中特定变量具有特定值?
Is there a python function to run a count where a specific variable has a certain value?
我可以使用
轻松地运行对整个数据集进行计数
import pandas as pd
data['eventcode'].value_counts()
生成列 'eventcode' 中所有唯一值的计数。现在我想 运行 相同的计数过程,但仅在不同列的值为 1 的情况下。我应该怎么做?提前致谢。
您可以先使用另一列进行过滤,然后执行 value_counts()
,如下所示:
data[data['othercolumn'] == 1]['eventcode'].value_counts()
您可以使用 df.loc
:
data.loc[data['othercolumn'] == 1,'eventcode'].value_counts()
基本上遍历发声向量并添加到你的计数器
cnt = 0
def set_count(row):
if row[different_column_name] == 1
cnt +=1
data['different_column_name'].apply(set_count)
如果您需要对多个唯一值执行此操作,您可以 groupby
+ size
然后 select 您需要的值作为结果的子集。
import pandas as pd
import numpy as np
np.random.seed(410112)
df = pd.DataFrame({'othercol': np.random.choice(range(3), 100),
'eventcode': np.random.choice(list('abc'), 100)})
s = df.groupby(['othercol', 'eventcode']).size()
#othercol eventcode
#0 a 10
# b 10
# c 9
#1 a 17
# b 15
# c 10
#2 a 10
# b 12
# c 7
# Where `df['othercol'] == 1`
s.loc[1]
#eventcode
#a 17
#b 15
#c 10
我可以使用
轻松地运行对整个数据集进行计数import pandas as pd
data['eventcode'].value_counts()
生成列 'eventcode' 中所有唯一值的计数。现在我想 运行 相同的计数过程,但仅在不同列的值为 1 的情况下。我应该怎么做?提前致谢。
您可以先使用另一列进行过滤,然后执行 value_counts()
,如下所示:
data[data['othercolumn'] == 1]['eventcode'].value_counts()
您可以使用 df.loc
:
data.loc[data['othercolumn'] == 1,'eventcode'].value_counts()
基本上遍历发声向量并添加到你的计数器
cnt = 0
def set_count(row):
if row[different_column_name] == 1
cnt +=1
data['different_column_name'].apply(set_count)
如果您需要对多个唯一值执行此操作,您可以 groupby
+ size
然后 select 您需要的值作为结果的子集。
import pandas as pd
import numpy as np
np.random.seed(410112)
df = pd.DataFrame({'othercol': np.random.choice(range(3), 100),
'eventcode': np.random.choice(list('abc'), 100)})
s = df.groupby(['othercol', 'eventcode']).size()
#othercol eventcode
#0 a 10
# b 10
# c 9
#1 a 17
# b 15
# c 10
#2 a 10
# b 12
# c 7
# Where `df['othercol'] == 1`
s.loc[1]
#eventcode
#a 17
#b 15
#c 10