用列中的列表整理数据帧的最佳方法

2024-03-28 22:37:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个杂乱无章的Tweet对象数据框。有两列包含列表:hashtagsexpanded_urls。我试图遵循整洁的数据原则,在一个行/列索引中只保留1个值。在

编辑:这个问题被标记为this answer的重复项,它只是将列表拆分成更多列。这对我不起作用,因为一条tweet中可能有可变数量的标签。在

以下是我的tweet数据帧的示例:

-----------------------------------------------------------
tweet_id | hashtags       | expanded_urls
-----------------------------------------------------------
  123    | ['lol','bff']  | ['fakeurl.com']
  124    | []             | ['url1.io', 'url2.expanded.co']

我有两种可能的方法来整理这些数据。在

1:只需将新行添加到DataFrame中,并将几乎所有行内容复制到

^{pr2}$

我不认为这是非常有效的,特别是因为有很多插入/追加操作。然而,将一个数据帧传递到单个scikit学习模型中会使事情变得非常简单。在

2:创建2个新的数据帧:

第一种是具有相应的tweet_ids的标签:

------------------
tweet_id | hashtag
------------------
123      | `lol`
123      | `bff`

另一个是URL及其对应的tweet_ids:

------------------
tweet_id | url
------------------
123      | `fakeurl.com`
124      | `url1.io`
124      | `url2.expanded.co`

这看起来更简洁,但我不完全确定如何修改原始数据帧;我是否只删除相应的列并保留3个单独的表?有没有一个好方法可以将这3个数据帧合并为1,或者每次我想知道哪些标签与tweet相关时都必须进行单独的查找?在


Tags: 数据iocomid列表标签urlstweet
2条回答

假设索引位于tweet_id如果不是,则可以使用.set_index()方法),对于方法2,可以尝试:

df['hashtags'].apply(pd.Series).stack().reset_index(level=1, drop=True).to_frame('hashtag')

Result:
               hashtag
tweet_id             
123               lol
123               bff

类似于expanded_urls

^{pr2}$

结果:

                  url
tweet_id                  
123            fakeurl.com
124                url1.io
124       url2.expanded.co

我在df上重新分配,将空列表转换为单个空字符串的列表

两列都在一起

from itertools import product

df = df.applymap(lambda x: x if x else [''])

pd.DataFrame([
    [t, h, e]
    for t, h_, e_ in df.values
    for h, e in product(h_, e_)
], columns=df.columns)

   tweet_id hashtags     expanded_urls
0       123      lol       fakeurl.com
1       123      bff       fakeurl.com
2       124                    url1.io
3       124           url2.expanded.co

或者没有itertools

^{pr2}$

单独

pd.DataFrame(dict(
    tweet_id=df.tweet_id.values.repeat(df.hashtags.str.len()),
    hashtags=np.concatenate(df.hashtags.values)
), columns=['tweet_id', 'hashtags'])

   tweet_id hashtags
0       123      lol
1       123      bff

^{4}$

相关问题 更多 >