我有与此类似的 DataFrame。如何添加具有在列之一中具有相同值的行名称的新列?例如:
有这个:
name building
a blue
b white
c blue
d red
e blue
f red
如何得到这个? name building in_building_with
a blue [c, e]
b white []
c blue [a, e]
d red [f]
e blue [a, c]
f red [d]
最佳答案
这是我只能想到的方法(最糟糕的):
r = df.groupby('building')['name'].agg(dict)
df['in_building_with'] = df.apply(lambda x: [r[x['building']][i] for i in (r[x['building']].keys()-[x.name])], axis=1)
df:
name building in_building_with
0 a blue [c, e]
1 b white []
2 c blue [a, e]
3 d red [f]
4 e blue [a, c]
5 f red [d]
联系方式:
building
blue {0: 'a', 2: 'c', 4: 'e'}
red {3: 'd', 5: 'f'}
white {1: 'b'}
dtype: object
r[x['building']].keys()-[x.name]
关于python - 使用具有相同列的数据创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65182169/