按行值索引列表中的熊猫新列

Ale*_*xSB 4 python filter dataframe pandas

我希望在 Pandas 数据框中创建一个新列,其中包含由 df 行值过滤的列表值。

df = pd.DataFrame({'Index': [0,1,3,2], 'OtherColumn': ['a', 'b', 'c', 'd']})

   Index OtherColumn
      0           a
      1           b
      3           c
      2           d

l = [1000, 1001, 1002, 1003]
Run Code Online (Sandbox Code Playgroud)

期望的输出:

  Index OtherColumn  Value
      0           a   -
      1           b   -
      3           c   1003
      2           d   - 
Run Code Online (Sandbox Code Playgroud)

我的代码:

df.loc[df.OtherColumn == 'c', 'Value'] = l[df.Index]
Run Code Online (Sandbox Code Playgroud)

它返回错误,因为 'df.Index' 不被识别为 int 而是一个列表(不是由 OtherColumn == 'c' 过滤)。

对于 R 用户,我正在寻找:

df[OtherColumn == 'c', Value := l[Index]]
Run Code Online (Sandbox Code Playgroud)

谢谢。

jez*_*ael 5

将列表转换为 numpy 数组以进行索引,然后在两侧按掩码过滤:

m = df.OtherColumn == 'c'
df.loc[m, 'Value'] = np.array(l)[df.Index][m]
print (df)
   Index OtherColumn   Value
0      0           a     NaN
1      1           b     NaN
2      3           c  1003.0
3      2           d     NaN
Run Code Online (Sandbox Code Playgroud)

或使用numpy.where

m = df.OtherColumn == 'c'
df['Value'] = np.where(m, np.array(l)[df.Index], '-')
print (df)
   Index OtherColumn Value
0      0           a     -
1      1           b     -
2      3           c  1003
3      2           d     -
Run Code Online (Sandbox Code Playgroud)

或者:

df['value'] = np.where(m, df['Index'].map(dict(enumerate(l))), '-')
Run Code Online (Sandbox Code Playgroud)