为每个符合另一列标准的索引添加一个增量列

时间:2016-10-17 18:04:50

标签: python pandas

我正在尝试从DataFrame生成一个列以进行分组。我知道非NaN下的每个NaN列都属于同一组。所以我写了这个循环(参见下文),但我想知道是否有更多的pandas / pythonic方式用apply或理解列表来编写它。

import pandas

>>> DF = pandas.DataFrame([134, None, None, None, 129374, None, None, 12, None],
                      columns=['Val'])
>>> a = [0]
>>> for i in DF['Val']:
        if i > 1:
            a.append(a[-1] + 1)
        else:
            a.append(a[-1])
>>> a.pop(0)  # remove 1st 0 which does not correspond to any rows
>>> DF['Group'] = a
>>> DF
        Val  Group
0     134.0      1
1       NaN      1
2       NaN      1
3       NaN      1
4  129374.0      2
5       NaN      2
6       NaN      2
7      12.0      3
8       NaN      3

1 个答案:

答案 0 :(得分:2)

使用pd.notnull识别非NaN值。然后使用cumsum创建Group列:

import pandas as pd

df = pd.DataFrame([134, None, None, None, 129374, None, None, 12, None],
                  columns=['Val'])
df['Group'] = pd.notnull(df['Val']).cumsum()
print(df)

产量

        Val  Group
0     134.0      1
1       NaN      1
2       NaN      1
3       NaN      1
4  129374.0      2
5       NaN      2
6       NaN      2
7      12.0      3
8       NaN      3