【问题标题】:combine rows in pandas after explode爆炸后在熊猫中合并行
【发布时间】:2021-04-06 23:54:45
【问题描述】:

我从 Twitter 收集了数据。我有多个列,但其中之一有问题:

tweets_data['Mentioned Users']

0        [{'username': 'HuntTerrorist', 'displayname': ...
1        [{'username': 'AttorneyCrump', 'displayname': ...
2                                                     None
3        [{'username': 'realDonaldTrump', 'displayname'...
4                                                     None
                               ...                        
19995                                                 None
19996                                                 None
19997                                                 None
19998                                                 None
19999                                                 None
Name: Mentioned Users, Length: 20000, dtype: object

我想从每一行获取用户名并将它们放回数据框中。

我试过explode命令:

exploded_df = tweets_data.explode('Mentioned Users')
user_df = exploded_df['Mentioned Users'].apply(pd.Series)
user_df['username']

0        HuntTerrorist
0          stinkytcat1
0           Nexussfire
0             BBCWorld
1        AttorneyCrump
             ...      
19995              NaN
19996              NaN
19997              NaN
19998              NaN
19999              NaN
Name: username, Length: 24886, dtype: object

此代码的问题在于它将每个提到的用户打印在不同的行中,从而扩展了总行数。由于长度不同,我无法将此列添加到原始列。所以我希望索引为 0 的所有用户名都在同一行(因为它们都在同一条推文中)。

有什么方法可以组合用户名或任何替代方法来做我想做的事吗?

【问题讨论】:

    标签: python pandas dataframe explode


    【解决方案1】:

    而不是exploding,为什么不直接从字典中索引所需的列,如下所示。

    df['Required column']=dictionary['required column']
    

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 2012-12-21
      • 2022-01-27
      • 2019-01-15
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 2021-08-03
      相关资源
      最近更新 更多