我正在尝试从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
答案 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