【问题标题】:How might I retrieve the values associated with indices of a Pandas Index object?如何检索与 Pandas Index 对象的索引关联的值?
【发布时间】:2021-09-29 05:43:26
【问题描述】:

假设我是

common_indices = df1.index.intersection(df2.index)

产生一个<class 'pandas.core.indexes.base.Index'> 对象,我如何检索与另一个数据帧关联的值(例如df3)。

尝试

sub_df3 = df3.where(df3.index == common_indices)

产生ValueError: Lengths must match to compare

【问题讨论】:

  • 你想用df3做什么?当您执行df3.index == common_indices 时,它试图做的是根据元素相等创建一个真假数组。

标签: python pandas indexing


【解决方案1】:

使用loc:

df3.loc[common_indices]

示例:

import numpy as np
import pandas as pd

df1 = pd.DataFrame(index = range(9), data=np.random.randint(low=100,size=(9,3)))
df2 = pd.DataFrame(index = [1,2,3,4,5], data=np.random.randint(low=100,size=(5,3)))
df3 = pd.DataFrame(index = range(9), data=np.random.randint(low=100,size=(9,3)))

>>> df1.index.intersection(df2.index)
Int64Index([1, 3, 5], dtype='int64')

>>> df3.loc[df1.index.intersection(df2.index)]
    0   1   2
1  90  33  99
3  90  41  43
5   3  10  12

【讨论】:

    【解决方案2】:
    df3.loc[common_indices]
    

    不要混淆:

    df3.loc(common_indices)
    

    产生TypeError

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多