python - 如何分组并将数组分配给python-pandas中的列?

标签 python pandas numpy dataframe

给定一个像这样的数据框df:

a     b    
2     nan
3     nan
3     nan
4     nan
4     nan
4     nan 
5     nan
5     nan 
5     nan
5     nan
...

一个关键规则是 a 中的每个数字 n 重复 n-1 行。我的预期输出是:

a     b    
2     1
3     1
3     2
4     1
4     2
4     3
5     1
5     2
5     3
5     4
...

因此b中的数m是一个从1n-1的列表。我这样试过:

df.groupby('a').apply(lambda x: np.asarray(range(x['a'].unique()[0]))) 

但是结果是一行中的列表,这不是我想要的。

你能告诉我如何实现它吗?提前致谢!

最佳答案

你需要cumcount :

df['b'] = df.groupby('a').cumcount() + 1
print (df)
   a  b
0  2  1
1  3  1
2  3  2
3  4  1
4  4  2
5  4  3
6  5  1
7  5  2
8  5  3
9  5  4

关于python - 如何分组并将数组分配给python-pandas中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39749653/

相关文章:

Pythonrequirements.txt 显示安装了哪个包?

python - 不是运算符,在 Python 中似乎是错误的?

python - '图像 "pyimage2"不存在'?

python - 如何串联或取消串联 pandas 数据框中的字符串值?

python - 在同一列中分隔多个变量

python - 尝试将 csv 文件读入 python 时内存不足

python - 从 Meshgrid reshape pandas DataFrame

python - 值错误 : cannot reshape array of size 235000 into shape (100, 64,64,2350)

python - 如果条件满足,Pandas Dataframe 找到第一个出现的位置

python - 相当于 NumPy 中的 "whos"命令