查找熊猫中不同行的值

  • 本文关键字:熊猫 查找 pandas
  • 更新时间 :
  • 英文 :


我有一个由数据和另一个数据帧组成的数据帧,其中包含一行携带索引。

data = {'col_1': [4, 5, 6, 7], 'col_2': [3, 4, 9, 8],'col_3': [5, 5, 6, 9],'col_4': [8, 7, 6, 5]}
df = pd.DataFrame(data)
ind = {'ind_1': [2], 'ind_2': [1],'ind_3': [3],'ind_4': [2]}
ind = pd.DataFrame(ind)

两者的列数相同。我想提取与存储在ind中的索引相对应的df的值,以便在末尾获得一行。

对于该数据,它应该是:[6, 4, 9, 6]。我尝试了df.loc[ind.loc[0]],但这当然给了我四个不同的行,而不是一个。

我的另一个想法是zip列和行,并对它们进行迭代。但我觉得应该有一个更简单的方法。

您可以转到NumPy域并在那里进行索引:

In [14]: df.to_numpy()[ind, np.arange(len(df.columns))]
Out[14]: array([[6, 4, 9, 6]], dtype=int64)

这将CCD_ 6从CCD_ 7和CCD_;因此我们得到了[2, 0][1, 1]等处的值


还有df.lookup,但它正在被弃用,所以…

In [19]: df.lookup(ind.iloc[0], df.columns)
~Anaconda3Scriptsipython:1: FutureWarning: The 'lookup' method is deprecated and will beremoved in a future version.You can use DataFrame.melt and DataFrame.locas a substitute.
Out[19]: array([6, 4, 9, 6], dtype=int64)

最新更新