从熊猫身上提取描述性文本



我有这个数据帧

df = pd.DataFrame(data = {"Store":["a","b","c","c","d"],"Goods":["x","x","x","y","x"]})
Store Goods
0     a     x
1     b     x
2     c     x
3     c     y
4     d     x

我想要一个描述性的输出,告诉我每个商品都可以在哪些商店使用,比如这个

The Good x is available at:
a
b
c
d
The Good y is available at:
c

所以我试了这个

for index, row in df.groupby(['Goods', 'Store']).count().iterrows():
print("The Good " + index[0] + " is available at:" + "n" + index[1] + "n" + "n")

得到了这个

The Good x is available at:
a
The Good x is available at:
b
The Good x is available at:
c
The Good x is available at:
d
The Good y is available at:
c

我该怎么做才对?

您可以尝试groupby

for x , y in df.groupby('Goods'):
print('The Good {} is avaliable at:'.format(x))
print (y['Store'].to_string(index=False))

The Good x is avaliable at:
a
b
c
d
The Good y is avaliable at:
c

最新更新