首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算一列重复不变的符号?

如何计算一列重复不变的符号?
EN

Stack Overflow用户
提问于 2022-11-01 19:51:52
回答 1查看 18关注 0票数 0

我有个专栏。我怎么能造一个新的列来计数重复的正负号呢?

代码语言:javascript
复制
col1
-5
-3
-7
4
5
-0.5
6
8
9

col1        count_sign
-5              3
-3              3
-7              3
4               2
5               2
-0.5            1
6               3
8               3
9               3

前3行是3,因为我们在前3行有3个负号,然后有2个正号和.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-01 19:59:57

代码语言:javascript
复制
# identify the change of signs among rows,
# making count as NaN, where sign is same, else 1
df['count']=np.where(np.sign(df['col1']).diff().eq(0),
        np.nan,
        1) 
# cumsum to group the rows
df['count']=df['count'].cumsum().ffill()

# groupby to take count of each group of rows and return groupsize using transform
df['count']=df.groupby('count')['col1'].transform('size')
df
代码语言:javascript
复制
col1    count
0   -5.0    3
1   -3.0    3
2   -7.0    3
3   4.0     2
4   5.0     2
5   -0.5    1
6   6.0     3
7   8.0     3
8   9.0     3

将符号添加到计数值

代码语言:javascript
复制
df['count']=np.where(np.sign(df['col1']).diff().eq(0),
        np.nan,
        1) 
df['count']=df['count'].cumsum().ffill()
df['count']=df.groupby('count')['col1'].transform('size')*np.sign(df['col1'])
df
代码语言:javascript
复制
    col1    count
0   -5.0    -3.0
1   -3.0    -3.0
2   -7.0    -3.0
3    4.0     2.0
4    5.0     2.0
5   -0.5    -1.0
6    6.0     3.0
7    8.0     3.0
8    9.0     3.0
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74281128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档