【问题标题】:How to modify a series to match indices of Pandas dataframe?如何修改系列以匹配 Pandas 数据框的索引?
【发布时间】:2022-01-10 00:10:01
【问题描述】:

考虑一个系列 ydtypefloat64),它有它的索引,例如

y = pd.Series((6.0, 1621.0, 4.6, 1479.9, 1520.0), index=(3608, 3652, 510, 941, 3007))

看起来像:

3608       6.000
3652    1621.000
510        4.600
941     1479.900
3007    1520.000
          ...   
dtype: float64 (length: 554)

有一个 Pandas 数据框 X,它有自己的索引和多个列,例如:

X = pd.DataFrame({'Col1':[1,2,3], 'Col2':[1,2,3]}, index=[510,3007,3652])

看起来像:

         Col1      Col2
510
3007
3652
... (dataframe length/count is 7)

我想修改系列y,以获得一个新系列,该系列基于数据帧索引排序并且具有与数据帧相同数量的样本(即来自y的7个索引匹配@987654331 @)。预计y 是:

510        4.600
3007    1520.000
3652    1621.000
          ...   
dtype: float64 (length: 7)

对此的任何帮助和建议将不胜感激。

【问题讨论】:

  • 感谢您的评论@Chris。我试过了,但出现错误:“MergeError:没有要执行合并的公共列。合并选项:left_on=None、right_on=None、left_index=False、right_index=False”。谢谢
  • sorry 是join not merge x.join(y.rename('test'))

标签: python pandas dataframe


【解决方案1】:

你可以使用Index.intersection方法:

out = y[y.index.intersection(X.index)]

Index.isin方法:

out = y[y.index.isin(X.index)]

过滤y 中也存在于X.index 中的索引。

如果保证X.indexy.index 的子集,那么您也可以使用X.index 进行过滤:

out = y[X.index]

输出:

3652    1621.0
510        4.6
3007    1520.0
dtype: float64

【讨论】:

    【解决方案2】:

    根据问题,鉴于系列 y 未命名/无法直接与数据框列名称匹配,以下工作:-

    通过将系列y 转换为带有to_frame() 的数据框,并按照@Chris(谢谢!)在问题评论中的建议使用X.merge() - 同时使用说明符以在其中一个上执行匹配索引,我们可以得到修改后的y

    modified_y = X.merge(y.to_frame(), left_index=True, right_index=True)
    

    y 是一个数据框,因此可以使用以下方法将其转换回系列形式:-

    modified_y = pd.Series(y.iloc[:,0].values, index = y.index)
    

    可能有更简单的替代方案,但这对我来说是有效的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多