繁体   English   中英

如何使用 pandas 计算另一列中每个值在一列中出现的次数?

[英]How to count number of occurrences of value in one column per value in other column using pandas?

我有一个 dataframe 具有唯一索引和列“用户”、“推文时间”和“推文 ID”。

我想计算每个用户重复的 tweet_time 值的数量。

users = ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C']
tweet_times = ['01-01-01 01:00', '02-02-02 02:00', '03-03-03 03:00', '09-09-09 09:00',
               '04-04-04 04:00', '04-04-04 04:00', '05-05-05 05:00', '09-09-09 09:00',
               '06-06-06 06:00', '06-06-06 06:00', '07-07-07 07:00', '07-07-07 07:00']

d = {'users': users, 'tweet_times': tweet_times} 
df = pd.DataFrame(data=d)

所需 Output

答:0

乙:1

C:2

我设法使用下面的代码获得所需的 output(A:0 除外)。 但是有没有更蟒蛇/有效的方法来做到这一点?

# group by both columns
df2 = pd.DataFrame(df.groupby(['users', 'tweet_times']).tweet_id.count())

# filter out values < 2
df3 = df2[df2.tweet_id > 1]

# turn multi-index level 1 into column
df3.reset_index(level=[1], inplace=True)

# final groupby
df3.groupby('users').tweet_times.count()

我们可以使用crosstab创建频率表,然后检查大于1的计数以创建 boolean 掩码,然后沿axis=1将此掩码sum

pd.crosstab(df['users'], df['tweet_times']).gt(1).sum(1)

 users
A    0
B    1
C    2
dtype: int64

这行得通,

df1 = pd.DataFrame(df.groupby(['users'])['tweet_times'].value_counts()).reset_index(level = 0)
df1.groupby('users')['tweet_times'].apply(lambda x: sum(x>1))

users
A    0
B    1
C    2
Name: tweet_times, dtype: int64

您可以将自定义 boolean 与您的groupby一起使用。

当一个值重复时, keep=False返回 True,否则返回 false。

# df['tweet_times'] = pd.to_datetime(df['tweet_times'],errors='coerce')

df.groupby([df.duplicated(subset=['tweet_times'],keep=False),'users']
                                                 ).nunique().loc[True]

       tweet_times
users             
A                0
B                1
C                2

可能有一个更简单的方法,但这是我现在能想到的:)

df.groupby("users")["tweet_times"].agg(lambda x: x.count() - x.nunique()).rename("count_dupe")

Output:

users
A    0
B    1
C    2
Name: count_dupe, dtype: int64

这对我来说看起来很pythonic:

df.groupby("users")["tweet_times"].count() - df.groupby("users")["tweet_times"].nunique()

Output:

users
A    0
B    1
C    2
Name: tweet_times, dtype: int64

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM