组和计数列具有多个值
给定此数据框架:
df = pd.DataFrame({
"names": [["Kevin, Jack"], ["Antoine, Mary, Johanne, Iv"], ["Ali"]],
"commented": [["Kevin, Antoine, Iv"], ["Antoine, Mary, Ali"], ["Mary, Jack"]],
}, index=["1", "2", "3"])
看起来像这样:
names commented
1 [Kevin, Jack] [Kevin, Antoine, Iv]
2 [Antoine, Mary, Johanne, Iv] [Antoine, Mary, Ali]
3 [Ali] [Mary, Jack]
我想获得一个新的数据框架,以计算所有人所做的所有评论。像:
Kevin | Jack | Antoine | Mary | Johanne | IV | Ali | |
---|---|---|---|---|---|---|---|
Kevin | 1 | 0 | 1 | 0 1 | 0 | 1 | 0 |
JATC | 0 | 0 | 1 0 1 0 ANTOINE 0 0 0 1 | 1 | 1 | 0 | 0 |
1 | 1 | 1 | 0 | 1 | 1 | 0 | 1 |
JOHANNE | 0 | 0 1 | 1 | 1 1 | 1 | 0 0 | 1 |
0 0 1 JOHANNE | 0 | 0 0 | 0 0 1 | 1 1 | IV 0 0 0 0 0 0 0 0 0 | 0 0 0 | 0 0 |
0 | 0 | 0 | 1 | 1 | 1 0 | 0 | 1 |
ali | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
这个数据框可能太小了,无法使其有意义,但是我的原始数据框架是100k行,数字将高于0和1。
我查看了各种选项使用Pivot_table和组的几种变体,但我似乎无法弄清楚。
df.pivot_table(index = 'names', columns= 'commented', aggfunc= 'count')
df.groupby('names').commented.apply(list).reset_index()
df.explode('names')['commented'].value_counts()
df.set_index('names').apply(pd.Series.explode).reset_index()
我尝试过的几乎所有解决方案都会给我错误: typeError:不可用的类型:'list'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试尝试将字符串列表爆炸为行列表,然后使用 .crosstab
You can try explode the list of strings to rows then use
pandas.crosstab
在您的示例输入中,
name
和注释
列中的每个元素是一个仅具有1个元素(字符串)的数组。不确定您的真实数据是这种情况。您可以将每个字符串划分为逗号,然后爆炸并旋转数据框:
In your sample input, each element in the
names
andcommented
columns is an array with only 1 element (a string). Not sure if that is the case with your real data.You can split each string by the comma, and then explode and pivot the dataframe:
这是使用
str.get_dummies()
输出的另一种方法:
Here is another way using
str.get_dummies()
Output: