【问题标题】:Pandas new column from indexing list by row value按行值索引列表中的 Pandas 新列
【发布时间】:2020-03-07 05:00:09
【问题描述】:

我希望在 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]

期望的输出:

  Index OtherColumn  Value
      0           a   -
      1           b   -
      3           c   1003
      2           d   - 

我的代码:

df.loc[df.OtherColumn == 'c', 'Value'] = l[df.Index]

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

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

df[OtherColumn == 'c', Value := l[Index]]

谢谢。

【问题讨论】:

  • 你的问题有错误吗?您的 df 代码与下面显示的不同?索引应该是 0,1,3,2 而不是 0,1,2,3?

标签: python pandas dataframe filter


【解决方案1】:

将列表转换为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

或者使用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     -

或者:

df['value'] = np.where(m, df['Index'].map(dict(enumerate(l))), '-')

【讨论】:

  • 谢谢。这样可行。但是,我的 df.Index 有 NaN,因此它是一个浮点数。你知道有什么快速的解决方法吗? np.array() 要求一个 int 对其进行切片...
  • @AlexSB - 如果使用最新版本的 pandas,则可以使用 this
  • @AlexSB - 对于第一个解决方案,例如添加最后一步 df['Value'] = df['Value'].astype("Int64")
【解决方案2】:

使用Series.where + Series.map:

df['value']=df['Index'].map(dict(enumerate(l))).where(df['OtherColumn']=='c','-')
print(df)

   Index OtherColumn value
0      0           a     -
1      1           b     -
2      3           c  1003
3      2           d     -

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2021-06-09
    • 2015-05-21
    • 1970-01-01
    • 2020-01-04
    相关资源
    最近更新 更多