在for循环中对pandas groupby对象进行操作

时间:2016-01-13 12:59:38

标签: python pandas

我有像

这样的数据框架
df = pd.DataFrame({'A': ['foo', 'bar','cat'] * 3,
             'B': ['i','who','he','am','are','said','satya','you','hello'],
             'C': [5, 2, 3, 4, 6, 9,12,23,45]})
df
Out[47]: 
A      B   C
0  foo      i   5
1  bar    who   2
2  cat     he   3
3  foo     am   4
4  bar    are   6
5  cat   said   9
6  foo  satya  12
7  bar    you  23
8  cat  hello  45

我将它们分组如下:

g = df.groupby('A')
for name, group in g:
     print(name)
     print(group)

获得o / p为:

bar
     A    B   C
1  bar  who   2
4  bar  are   6
7  bar  you  23
cat
     A      B   C
2  cat     he   3
5  cat   said   9
8  cat  hello  45
foo
     A      B   C
0  foo      i   5
3  foo     am   4
6  foo  satya  12

所以我需要做的是我想迭代每个组并再次为每个组我将迭代(我不知道)对列进行迭代并在列B处连接值以便我可以得到一些东西像

bar = who are you
cat = he said hello
foo = i am satya

我无法对此进行agg功能。谁能建议怎么做?

1 个答案:

答案 0 :(得分:3)

IIUC你可以requestPermissions() groupby然后A lambda到apply字符串值:

join