python - python中的数据框操作

标签 python pandas numpy dataframe logic

我有下面给出的输入数据帧。对于 ID 的每个第一个唯一元素行,必须在输出数据帧 Zeros_For_UniqueID 列中将其写入零。然后,在唯一 ID 出现整数之前,应从 Count 变量中对连续的零进行计数,并且必须将其放入输出列 Zeros_For_UniqueID .

输入数据框:

ID  Count
1234    1
1234    2
1234    0
1234    0
1234    0
1234    1
1234    1
5678    1
5678    5
5678    4
5678    0
1111    0
1111    0
1111    1
1111    2
1111    0
1111    0
1111    2

输出数据框

ID  Count   Zeros_For_UniqueID
1234    1   0
1234    2   0
1234    0   0
1234    0   1
1234    0   2
1234    1   3
1234    1   0
5678    1   0
5678    5   0
5678    4   0
5678    0   0
1111    0   0
1111    0   1
1111    1   2
1111    2   0
1111    0   0
1111    0   1
1111    2   2

谁能帮我解决这个问题。我是 python 新手,正在尝试解决这个问题以供进一步研究。谢谢!

最佳答案

我不确定速度,但这将达到你所需要的,你需要groupby+cumsum+shift

df['New']=df.groupby('ID').\
     apply(lambda x : x.groupby(x.Count.ne(0).cumsum().shift().fillna(False)).cumcount()).\
       sort_index(level=1).values
df
Out[323]: 
      ID  Count  New
0   1234      1    0
1   1234      2    0
2   1234      0    0
3   1234      0    1
4   1234      0    2
5   1234      1    3
6   1234      1    0
7   5678      1    0
8   5678      5    0
9   5678      4    0
10  5678      0    0
11  1111      0    0
12  1111      0    1
13  1111      1    2
14  1111      2    0
15  1111      0    0
16  1111      0    1
17  1111      2    2

关于python - python中的数据框操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48574444/

相关文章:

Python:如何过滤字典?

python - numpy View 如何知道它引用的值在原始 numpy 数组中的位置?

python - Fisher 信息计算扩展

python - input() vs raw_input() 相关安全问题的简单解释

python - 如何在事件循环之外运行协程?

python - 替换 NumPy 中的迭代

python user32.GetMessage永远不会退出

python - 如何根据小时标准获得每天每组的最小值

python - 将 API 转换为 Pandas DataFrame

python - 如何按对角线填充矩阵?