熊猫如何获得当前连续正数的数量?

时间:2017-05-22 02:23:11

标签: python pandas

pandas如何获得当前连续正数的数量?

在Python Pandas中,我有一个包含以下格式的列和记录的数据框:

private class Voice implements TextToSpeech.OnInitListener {
    Context context = getApplicationContext();
    TextToSpeech tts = new TextToSpeech(context, this);

    public void onInit(int initStatus) {
        if (initStatus == TextToSpeech.SUCCESS) {
            tts.setLanguage(Locale.US);
            // try it!
            voice.say("Can you hear this sentence?");
            // If you want to another "say", check this log.
            // Your voice will say after you see this log at logcat.
            Log.i("TAG", "TextToSpeech instance initialization is finished.");
        }
    }

    private void say(String announcement) {
        tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, null);
    }
}

如何获得当前连续正数的数量?

例如,我想要结果像这样(添加一列y代表连续的正数)

In [7]: d = {'x' : [1,-1,1,1,-1,1,1,1,-1,1,1,1,1,-1,1,1,1,1,1]}

In [8]: df = pd.DataFrame(d)

In [9]: df
Out[9]:
    x
0   1
1  -1
2   1
3   1
4  -1
5   1
6   1
7   1
8  -1
9   1
10  1
11  1
12  1
13 -1
14  1
15  1
16  1
17  1
18  1

2 个答案:

答案 0 :(得分:2)

<强> pandas
笨拙,但应该工作

p = df.y > 0
c = p.cumsum()
c - c.mask(p).ffill().fillna(0).astype(int)

答案 1 :(得分:0)

试试这个。我也使用了随机混乱的1而不是1,它与你的数据不同:

          x
    0     1
    1    -1
    2     1
    3     1
    4     1
    5    -1
    6     1
    7     1
    8     1
    9     1
    10   -1


y = [] #Create a list outside a counter function

    def count(df):
        counter = 0
        for item in df:
            if item > 0:
                counter += 1
                y.append(counter)
            else:
                counter = 0
                y.append(counter)
        return y

count(df['x']) #run function

df['y'] = y #add column based on list


      y
0     1
1     0
2     1
3     2
4     3
5     0
6     1
7     2
8     3
9     4
10    0