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

标签 python pandas dataframe group-by pandas-groupby

所以我有数据框:

>>> 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 行...进入无限循环。请指教

最佳答案

我相信您正在沿着第 0th 列索引 + cumcount 查找 groupby:

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

关于python - Pandas:如何在分组行中添加行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49135821/

相关文章:

python - 在 Pandas 中加入键不相等的地方

python - 检查值是否在 pandas.DataFrame 的列列表中

r - 从数据框中提取单独的列

python - Pandas fillna() 按特定顺序排列

python - Pandas:合并数据帧并仅保留与合并的唯一对关联的最小值

Python、Windows 和多处理

Python Tkinter返回csv文件目录

python - 乘以计数器对象的元素

python - 从 Pandas 中给定的单元格值获取行

python - 删除 Pandas 数据框中包含特定值的列和行