我有一个包含文本的熊猫数据框架,每个文本可以属于一个流派和几个类别。由于每个文本可以属于多个类别,因此每个列都是一次性编码的。
下面是一个例子(实际的数据帧有更多的类别):
df = pd.DataFrame({'text':{0:'This is an example string', 1: 'this is another example', 2:'and another',3:'and yet another example'},'genre':{0: 'fiction', 1: 'fiction', 2: 'scientific', 3: 'news'},'category_nature':{0: 1, 1: 1, 2: 0, 3:1}, 'category_history':{0: 1, 1: 0, 2: 0, 3:1},'category_art':{0: 0, 1: 0, 2: 1, 3: 0}})
我正在寻找一种方法,既可以在类别上获得像value_counts()这样的东西,也可以在流派上获得,就像这样:
我首先尝试更改one-hot-encoded列的格式,但后来丢失了"genre“列。
df_new = df.drop(columns=['text','genre']);
count = df_new.sum().sort_values(ascending=False)
我还查看了下面的帖子,但它并不完全是我想要的。
Python: get a frequency count based on two columns (variables) in pandas dataframe some row appers
发布于 2021-08-26 07:47:38
您可以使用melt
和groupby
(df.melt(id_vars=['text', 'genre'], var_name='category', value_name='count')
.groupby(['genre', 'category'])
['count'].sum()
# below is for formatting only
.reset_index()
.query('count > 0')
.assign(category=lambda d:d['category'].str[9:])
)
输出:
genre category count
1 fiction history 1
2 fiction nature 2
4 news history 1
5 news nature 1
6 scientific art 1
发布于 2021-08-26 07:49:23
这就是你要找的东西吗?
df.groupby('genre').sum().reset_index().melt(id_vars='genre')
genre variable value
0 fiction category_nature 2
1 news category_nature 1
2 scientific category_nature 0
3 fiction category_history 1
4 news category_history 1
5 scientific category_history 0
6 fiction category_art 0
7 news category_art 0
8 scientific category_art 1
https://stackoverflow.com/questions/68941493
复制相似问题