How I can count the number of repetitive positive or negative elements in each row?
Suppose I have the following data:
ski 2020 2021 2022 2023 2024 2025
book 1.2 5.6 8.4 -2 -5 6
jar 4.2 -5 -8 2 4 6
kook -4 -5.2 -2.3 -5.6 -7 8
The output is a list for each row that counts the number of similar signs. For example in the first row we have 3 positive elements and then 2 negative and again one positive. So the output is [3,-2,1]. and for 2 other rows the output is as follows:
jar [1,-2,3]
kook [-5,1]
Let us try:
s = np.sign(df.set_index('ski').stack())
s.groupby([pd.Grouper(level=0), s.diff().ne(0).cumsum()]).sum().groupby(level=0).agg(list)
ski
book [3.0, -2.0, 1.0]
jar [1.0, -2.0, 3.0]
kook [-5.0, 1.0]
dtype: object
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments