如何用 Pandas 数据框中的列值替换单元格中的索引值

How to replace indices values in a cell with the column value in a Pandas dataframe

我有一个具有唯一 ID 和少量属性的数据集。我在Python中执行k-d树得到三个最近邻的每个id的索引如下图所示:

上图中的“Index”是Pandasdataframe自带的默认索引。我想要如下图所示格式的输出:

这可以在 excel 中使用 vlookup 轻松完成,但如何在 Python 中完成?

使用

In [289]: cols = ['neighbor1', 'neighbor2', 'neighbor3']

In [290]: df[cols].replace(df.set_index('index')['id'].to_dict())
Out[290]:
  neighbor1 neighbor2 neighbor3
0        u1        u4        u3
1        u2        u3        u2
2        u3        u1        u2
3        u4        u1        u2

In [291]: df[cols] = df[cols].replace(df.set_index('index')['id'].to_dict())

In [292]: df
Out[292]:
   index  id neighbor1 neighbor2 neighbor3
0      0  u1        u1        u4        u3
1      1  u2        u2        u3        u2
2      2  u3        u3        u1        u2
3      3  u4        u4        u1        u2

使用 replace Series:

df = df.replace(df['id'])
#or convert to dict (first solution)
#df = df.replace(df['id'].to_dict())
print (df)
   id neighborl neighbor2 neighbor3
0  u1        u1        u4        u3
1  u2        u2        u3        u2
2  u3        u3        u1        u2
3  u4        u4        u1        u2

另一个解决方案:

cols = ['neighbor1', 'neighbor2', 'neighbor3']
df[cols] = df[cols].applymap(df['id'].to_dict().get)
print (df)
   id neighbor1 neighbor2 neighbor3
0  u1        u1        u4        u3
1  u2        u2        u3        u2
2  u3        u3        u1        u2
3  u4        u4        u1        u2

如果想要更动态的解决方案:

#select columns starting by neighbor
cols = df.filter(regex='^neighbor').columns
print (cols)
Index(['neighbor1', 'neighbor2', 'neighbor3'], dtype='object')

df[cols] = df[cols].replace(df['id'])
print (df)
   id neighbor1 neighbor2 neighbor3
0  u1        u1        u4        u3
1  u2        u2        u3        u2
2  u3        u3        u1        u2
3  u4        u4        u1        u2

#create mask by columns names starting by neighbor
mask = df.columns.str.startswith('neighbor')
print (mask)
[False  True  True  True]

df.loc[:, mask] = df.loc[:, mask].replace(df['id'])
print (df)
   id neighbor1 neighbor2 neighbor3
0  u1        u1        u4        u3
1  u2        u2        u3        u2
2  u3        u3        u1        u2
3  u4        u4        u1        u2

试试这个,

print df.replace(df['id'].to_dict())

输入:

       id  neighbor1  neighbor2  neighbor3
index                                     
0      u1          0          3          2
1      u2          1          2          1
2      u3          2          0          1
3      u4          3          0          1

输出:

       id neighbor1 neighbor2 neighbor3
index                                  
0      u1        u1        u4        u3
1      u2        u2        u3        u2
2      u3        u3        u1        u2
3      u4        u4        u1        u2
df = pd.DataFrame([['u1', 0, 3, 2], ['u2', 1, 2, 1], ['u3', 2, 0, 1], ['u4', 3, 0, 1]], columns=['id', 'n1', 'n2', 'n3'])
print df
   id  n1  n2  n3
0  u1  0   3   2 
1  u2  1   2   1 
2  u3  2   0   1 
3  u4  3   0   1 

print df.assign(n1=df.n1.map(df.id),
                n2=df.n2.map(df.id),
                n3=df.n3.map(df.id))    

   id  n1  n2  n3
0  u1  u1  u4  u3
1  u2  u2  u3  u2
2  u3  u3  u1  u2
3  u4  u4  u1  u2