创建一个新的数据框,为每个用户计算正面和负面的推文

时间:2019-09-21 18:02:07

标签: python pandas dataframe

我具有以下DataFrame:

enter image description here

它包含user_id,tweet,位置和tweet的分类,分别为正数和负数。

我想创建一个按用户ID分组的新数据框,因为每个用户在数据框中有多个推文。数据框应包含以下列:

  1. user_id
  2. 该user_id否定推文的数量
  3. 该user_id的正面推文计数
  4. 用户位置

必需的样品输出

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()

但是,它与所需的输出不匹配。

谢谢

1 个答案:

答案 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(),
)))