【问题标题】:Pandas split string values in column to multiple rowsPandas 将列中的字符串值拆分为多行
【发布时间】:2021-10-01 19:19:24
【问题描述】:

是的,我查过其他问题,但我仍然无法正确回答。

我有一个多列的 df,像这样

id, hashtag
1234, ['hash1', 'hash2', 'hash3']
1254, [hash1']
1777, ['hash5']

我希望输出中的每个主题标签都有一行,然后将相同的标签分组以便获得它们的频率,例如:

hashtag, count
hash1, 2
hash2, 1
hash3, 1
hash5, 1

但我得到的输出计数错误。这是我的代码:

hashtags_df = df['hashtags'].value_counts().fillna(0).rename_axis('hashtags').reset_index(name='counts')
hashtags_df = df['hashtags'].reset_index(name='index')
hashtags_df['hashtags'] =  hashtags_df['hashtags'].apply(lambda x: x.replace('[','').replace(']','')) #doing it because it seems like they're not lists. I'm using twint to extract tweets by the way
hashtags_df['hashtags'] = hashtags_df['hashtags'].astype('string') #the dtype otherwise is an obj

hashtags_df.nunique().sum()


new_df = pd.DataFrame(hashtags_df.hashtags.str.split(',').tolist(), index=hashtags_df.counts).stack()
new_df = new_df.reset_index([0, 'counts'])
new_df.columns =['counts', 'hashtags']
new_df = new_df['hashtags'].value_counts().rename_axis('hashtags').reset_index(name="counts")

print(new_df)

我多次修改代码,现在它搞砸了。感觉解决方案很简单,但我找不到。我该怎么办?

【问题讨论】:

  • 这可能以前被问过。如果您的列值看起来不是真正的列表而是字符串,可以尝试from ast import literal_eval; df.hashtag.apply(literal_eval).explode().value_counts() 首先将它们转换为列表。

标签: python python-3.x pandas twitter


【解决方案1】:

您可以将explode 函数与value_counts 一起使用。不需要其他任何东西。

df.hashtag \
  .explode() \
  .value_counts() \
  .reset_index() \
  .rename(columns={"index": "hashtag", "hashtag": "counts"})

  hashtag  counts
0   hash1       2
1   hash5       1
2   hash2       1
3   hash3       1

【讨论】:

  • 它不起作用,因为输出仍然有 ['hash1', 'hash2', 'hash3', 'hash4'] 之类的东西,我需要它们分开
  • 不确定你的意思,它对我来说很好用
  • 它不适合我...该列不是字符串类型,我也收到错误 AttributeError: 'Series' object has no attribute 'hashtags'
  • 你在哪里看到我写hashtags?我也不把它当作一个字符串,我把它当作一个列表列表
  • 如果他的列是字符串类型,那么是的,这是正确的
【解决方案2】:
import pandas

data = [
    [1234, ['hash1', 'hash2', 'hash3']],
    [1254, ['hash1']],
    [1777, ['hash5']]
]

df = pd.DataFrame(data, columns = ["id", "hashtag"])

output = df.explode("hashtag") \
          .groupby("hashtag") \
              .count().reset_index() \
                  .rename(columns={"id": "count"})

输出:

  hashtag  count
0   hash1      2
1   hash2      1
2   hash3      1
3   hash5      1

【讨论】:

  • 它不起作用,输出和以前一样。字符串不拆分
猜你喜欢
  • 2022-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-30
相关资源
最近更新 更多