简体   繁体   English

Python pandas 如何将累积计数器添加到相邻列?

[英]Python pandas how to add an accumulation counter to a neighboring column?

I have a csv file with something like this column我有一个 csv 文件,其中包含类似此列的内容

Comulative累积性
-1 -1
-3 -3
-4 -4
1 1
2 2
5 5
-1 -1
-4 -4
-8 -8
1 1
3 3
5 5
10 10

I would like to add an internal column counting the number of sign shifts我想添加一个内部列来计算符号移位的数量

To get something like this得到这样的东西

Comulative累积性 Score分数
-1 -1 1 1
-3 -3 2 2
-4 -4 3 3
1 1 1 1
2 2 2 2
5 5 3 3
-1 -1 1 1
-4 -4 2 2
-8 -8 3 3
1 1 1 1
3 3 2 2
5 5 3 3
10 10 4 4

In my original csv file, the Comulative column usually does not change the sign from about 100 to 500 lines here, for clarity, it changes so often !在我原来的 csv 文件中,Comulative 列通常不会将符号从大约 100 行更改为 500 行,为了清楚起见,它经常更改!

Can you tell me how to do it better?你能告诉我如何做得更好吗?

Get the sign with numpy.sign , then use a custom groupby with cumcount :使用numpy.sign获取标志,然后使用自定义groupbycumcount

# get sign
s = np.sign(df['Comulative'])
# group by consecutive signs
group = s.ne(s.shift()).cumsum()
# enumerate
df['Score'] = s.groupby(group).cumcount().add(1)

NB.注意。 if you want to consider 0 as part of the positive numbers, use s = df['Comulative'].gt(0) .如果您想将 0 视为正数的一部分,请使用s = df['Comulative'].gt(0)

output: output:

    Comulative  Score
0           -1      1
1           -3      2
2           -4      3
3            1      1
4            2      2
5            5      3
6           -1      1
7           -4      2
8           -8      3
9            1      1
10           3      2
11           5      3
12          10      4

mozway's usage of np.sign is far prettier, but for a more drawn out answer - you could do something like this. mozway 对np.sign的使用要漂亮得多,但是要获得更详尽的答案-您可以做这样的事情。

# Marks true every time the previous value is positive, 
# and the current is negative or visa versa.
groups = (df.Comulative.lt(0) & df.Comulative.shift().gt(0) 
         | df.Comulative.gt(0) & df.Comulative.shift().lt(0)).cumsum()

df['Score'] = df.groupby(groups).cumcount().add(1)

Output: Output:

    Comulative  Score
0           -1      1
1           -3      2
2           -4      3
3            1      1
4            2      2
5            5      3
6           -1      1
7           -4      2
8           -8      3
9            1      1
10           3      2
11           5      3
12          10      4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM