我有一个包含多个标识符的数据帧。我想为标识符的每个唯一组合创建一个新的“组标识符”——稍后,我想使用statsmodels
运行回归。也就是说,我有
id1 id2 id3
A 1 100
A 1 101
B 1 100
B 1 100
我想得到
id1 id2 id3 groupid
A 1 100 0
A 1 101 1
B 1 100 2
B 1 100 2
以id1
、id2
、id3
作为标识符集。我知道我可以获得unique()
来获得唯一的组,但是如何有效地将行编码到它们所属的唯一组中呢?你知道吗
调整@Bernie的答案以适应潜在的“NaN”:
# get a DataFrame with just the unique "keys"
df2 = df.replace(np.NaN, -1)
g = df2.groupby([u'id1',u'id2',u'id3'])
gdf = pd.DataFrame(g.groups.keys(),columns=df.columns)
gdf = gdf.replace(-1, np.NaN)
# an idea is to re-use the index as the 'group_id'
# the next three commands support that
gdf.sort([u'id1',u'id2',u'id3'],inplace=True)
gdf.reset_index(drop=True,inplace=True)
gdf['group_id'] = gdf.index
# merge on the three id columns
mdf = df.merge(gdf,how='inner',on=df.columns.tolist())
当然有无数的解决办法。这就是我的目的。。。你知道吗
产生:
这就是你要找的吗?你知道吗
以下是输出:
相关问题 更多 >
编程相关推荐