【问题标题】:Getting Descriptive Text out of Pandas从 Pandas 中获取描述性文本
【发布时间】:2022-01-24 22:02:50
【问题描述】:

我有这个数据框

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

我怎样才能做到正确?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以试试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
    

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      相关资源
      最近更新 更多