我有一个这样的 csv 文件:
word, tag, counter
I, Subject, 1
Love, Verb, 3
Love, Adjective, 1
我想创建一个数据框,其中列是单词和标签列表,如下所示:
Word Subject Verb Adjective
I 1 0 0
Love 0 3 1
我如何设法用 pandas 做到这一点?
请您参考如下方法:
您可以使用 pivot :
df = df.pivot(index='word', columns='tag', values='counter').fillna(0).astype(int)
print (df)
tag Adjective Subject Verb
word
I 0 1 0
Love 1 0 3
df = df.set_index(['word','tag'])['counter'].unstack(fill_value=0)
print (df)
tag Adjective Subject Verb
word
I 0 1 0
Love 1 0 3
但是如果得到:
ValueError: Index contains duplicate entries, cannot reshape
然后需要通过 pivot_table 中的一些 aggfunc 进行聚合:
print (df)
word tag counter
0 I Subject 1
1 Love Verb 3
2 Love Adjective 1 <-duplicates for Love and Adjective
3 Love Adjective 3 <-duplicates for Love and Adjective
df = df.pivot_table(index='word',
columns='tag',
values='counter',
aggfunc='mean',
fill_value=0)
print (df)
tag Adjective Subject Verb
word
I 0 1 0
Love 2 0 3
另一种使用 groupby 和 unstack 的解决方案:
df = df.groupby(['word','tag'])['counter'].mean().unstack(fill_value=0)
print (df)
tag Adjective Subject Verb
word
I 0 1 0
Love 2 0 3
