我具有以下DataFrame:
它包含user_id,tweet,位置和tweet的分类,分别为正数和负数。
我想创建一个按用户ID分组的新数据框,因为每个用户在数据框中有多个推文。数据框应包含以下列:
必需的样品输出
user_id positive_tweets negative_tweets Location
418 1 0 CA
521 1 0 CA
997 0 1 LA
1135 1 0 LA
BlackFox先生针对我之前提出的我没有正确询问的问题提出了此代码。
df.groupby(['user_id','classification'])['user_id'].count()
但是,它与所需的输出不匹配。
谢谢
答案 0 :(得分:2)
我希望这就是您想要的。
df.groupby(['user_id', 'Location']).apply(lambda x: pd.Series(dict(
positive_tweets=(x.classification == 'positive').sum(),
negative_tweets=(x.classification == 'negative').sum(),
)))