![](/img/trans.png)
[英]Find index of consecutive values in a list, if from negative values goes to positive using Python
[英]Count consecutive positive and negative values in a list
我創建了一個包含兩列的數據框,並希望根據來自其他數組的值的計數來附加它們。
cols = ['count_pos','count_neg']
df_count = pd.DataFrame(columns=cols)
我有數組 y,其值類似於 y = [1,-1,-1,1,1,1,1,-1,-1]
現在我想更新 y 中值的每個變化,計算這些出現次數並附加到相應的列。
for i in range(1,10):
if y[i] == -1:
print(y[i])
if count_pos > 0:
df_count.loc['count_pos'].append = count_pos
count_pos = 0
count_neg = count_neg - 1
else:
if count_neg< 0:
print(count_neg)
df_count.loc['count_neg'].append = count_neg
count_neg = 0
count_pos = count_pos + 1
但我沒有得到結果。請讓我知道如何將值附加到數據框列。
我想要的輸出是 df_count
count_pos count_neg
1 -2
4 -2
使用groupby
計算連續的正/負值組:
s = pd.Series(y)
v = s.gt(0).ne(s.gt(0).shift()).cumsum()
pd.DataFrame(
v.groupby(v).count().values.reshape(-1, 2), columns=['pos', 'neg']
)
pos neg
0 1 2
1 4 2
改編自@cs95 的回答:
a = pd.Series([-1, 2, 15, 3, 45, 5, 23, 0, 6, -4, -8, -5, 3,
-9, -7, -36, -71, -2, 25, 47, -8])
def pos_neg_count(a):
v = a.ge(0).ne(a.ge(0).shift()).cumsum()
vals = v.groupby(v).count().values
cols = ['pos', 'neg'] if a[0] >= 0 else ['neg', 'pos']
try:
result = pd.DataFrame(vals.reshape(-1, 2), columns=cols)
except ValueError:
vals = np.insert(vals, len(vals), 0)
result = pd.DataFrame(vals.reshape(-1, 2), columns=cols)
return result
pos_neg_count(a)
# neg pos
# 0 1 8
# 1 3 1
# 2 5 2
# 3 1 0
我認為,這將處理被重塑的數組具有奇數的情況。 的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.