python - Pandas ,对于一列中的每个唯一值,在另一列中获取唯一值

标签 python pandas

我有一个数据框,其中每一行都包含与单个 Reddit 评论(例如作者、subreddit、评论文本)相关的各种元数据。

我想做以下事情:对于每个作者,我想获取他们在其中发表评论的所有 subreddits 的列表,并将此数据转换为 pandas 数据框,其中每一行对应一个作者,以及所有的列表他们发表评论的独特子版 block 。

我目前正在尝试以下的一些组合,但无法理解:

尝试 1:

group = df['subreddit'].groupby(df['author']).unique()
list(group) 

尝试 2:

from collections import defaultdict
subreddit_dict  = defaultdict(list)

for index, row in df.iterrows():
    author = row['author']
    subreddit = row['subreddit']
    subreddit_dict[author].append(subreddit)

for key, value in subreddit_dict.items():
    subreddit_dict[key] = set(value)

subreddit_df = pd.DataFrame.from_dict(subreddit_dict, 
                            orient = 'index')

最佳答案

这里有两种策略可以做到这一点。毫无疑问,还有其他方法。

假设您的数据框看起来像这样(显然有更多列):

df = pd.DataFrame({'author':['a', 'a', 'b'], 'subreddit':['sr1', 'sr2', 'sr2']})

>>> df
  author subreddit
0      a       sr1
1      a       sr2
2      b       sr2
...

解决方案 1:groupby

比解决方案 2 更直接,并且类似于您的第一次尝试:

group = df.groupby('author')

df2 = group.apply(lambda x: x['subreddit'].unique())

# Alternatively, same thing as a one liner:
# df2 = df.groupby('author').apply(lambda x: x['subreddit'].unique())

结果:

>>> df2
author
a    [sr1, sr2]
b         [sr2]

作者是索引,单列是他们活跃的所有子版 block 的列表(根据您的描述,这就是我解释您想要输出的方式)。

如果你希望每个子版 block 都在一个单独的列中,这可能更有用,具体取决于你想用它做什么,你可以在之后这样做:

df2 = df2.apply(pd.Series)

结果:

>>> df2
          0    1
author          
a       sr1  sr2
b       sr2  NaN

解决方案 2:遍历数据框

您可以创建一个包含所有唯一作者的新数据框:

df2 = pd.DataFrame({'author':df.author.unique()})

然后只获取他们活跃的所有独特子目录的列表,并将其分配给新列:

df2['subreddits'] = [list(set(df['subreddit'].loc[df['author'] == x['author']])) 
    for _, x in df2.iterrows()]

这给了你这个:

>>> df2
  author  subreddits
0      a  [sr2, sr1]
1      b       [sr2]

关于python - Pandas ,对于一列中的每个唯一值,在另一列中获取唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48979604/

相关文章:

python - 将 x,y 坐标放入 bin 中

python - Pyspark数据框获取列的所有值

python / Pandas : How to increment each row based on string condition

python - 在Python中获取/过滤与属性/键匹配的对象列表中的第一项

python - Firestore 数据库写入的性能?

python - 在 python 中使用 Pandas 将列附加到数据框

python - 全局名称 'inf' 未定义

python - 长/宽数据到宽/长

python - 什么是 python 生成器?

linux - 如何在 python 中将 '>' 作为参数传递给终端