Pandas:如何在分组行中添加行数

时间:2018-03-06 16:37:45

标签: python pandas dataframe group-by pandas-groupby

所以我有DataFrame:

>>> df2
      text
0  0  a  
0  1  b
0  2  c
0  3  d
1  4  e
1  5  f  
1  6  g  
2  7  h  
2  8  1

如何创建另一列,其中包含level = 0索引中每行的计数器?

我尝试过以下代码(我需要获取df ['counter']列):

current_index = ''
for index, row in df.iterrows():
  if index[0] != current_index:
    current_index = index[0]
    df[(df.index == current_index)]['counter'] = np.arange(len(df[(df.index == current_index)].index))

以及以下代码:

df2 = pd.DataFrame()
for group, df in df1.groupby('level_0_column'):
  df0 = df0.sort_values(by=['level_1_column'])
  df['counter'] = list(df.reset_index().index.values + 1)
  df2 = df2.append(df0)

我在DataFrame中有大约650K行...进入无限循环。请建议

1 个答案:

答案 0 :(得分:2)

我相信你在0 th 列索引+ groupby上寻找cumcount

df['counter'] = df.groupby(level=0).cumcount() + 1
df

    text  counter
0 0    a        1
  1    b        2
  2    c        3
  3    d        4
1 4    e        1
  5    f        2
  6    g        3
2 7    h        1
  8    1        2