【问题标题】:How to select values from a dataframe by a series of column names?如何通过一系列列名从数据框中选择值?
【发布时间】:2021-09-23 06:14:43
【问题描述】:

我有一个数据框df

    A   B
0   1   4
1   2   5
2   3   6

还有一个系列s

0    A
1    B
2    A

现在我想从df 中选择列名在s 中指定的值。预期结果是:

0    1  <- from column A
1    5  <- from column B
2    3  <- from column A

我怎样才能有效地完成这项工作?

【问题讨论】:

    标签: python pandas numpy data-science


    【解决方案1】:

    Index.get_indexer 用于Series 的索引,并通过2d array 中的numpy 索引选择值:

    a = df.to_numpy()
    b = a[np.arange(len(df)), df.columns.get_indexer(s)]
    print (b)
    [1 5 3]
    

    s1 = pd.Series(b, s.index)
    print (s1)
    0    1
    1    5
    2    3
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多