【问题标题】:Retaining only the Column Rows from chosen DF in the calculation results在计算结果中仅保留所选 DF 中的列行
【发布时间】:2017-08-07 13:01:44
【问题描述】:

这是一个后续问题:How to treat NaN or non aligned values as 1s or 0s in multiplying pandas DataFrames

我有以下数据:

df1 = pd.DataFrame({"x":[1, 2, 3, 4, 5], 
    "y":[3, 4, 5, 6, 7]}, 
    index=['a', 'b', 'c', 'd', 'e'])

df2 = pd.DataFrame({"y":[1, NaN, 3, 4, 5], 
    "z":[3, 4, 5, 6, 7]}, 
    index=['b', 'c', 'd', 'e', 'f'])

我想将df1df2df2 中的所有数据相乘,因为df1 中没有对应的条目,而df2 中只有行和列。

例如

print (df1.mul(df2).fillna(df2))

print (df1.mul(df2).combine_first(df2))

给予:

    x     y    z
a NaN   NaN  NaN
b NaN   4.0  3.0
c NaN   NaN  4.0
d NaN  18.0  5.0
e NaN  28.0  6.0
f NaN   5.0  7.0

但我想到达:

   y     z
b 4.0   3.0
c NaN   4.0
d 18.0  5.0
e 28.0  6.0
f 5.0   7.0

注意:

  • 可以有合法的NaNInf-Inf 值。
  • 列/行可能并不总是在生成的 DF 的左侧或右侧/顶部或底部,尽管在上面的示例中是这种情况。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我相信最简单的方法是获取索引和列的交集,如下所示:

    In [1142]: c = df1.columns & df2.columns
    
    In [1143]: i = df1.index & df2.index
    

    现在,只需索引并与 df.loc 相乘:

    In [1145]: df2.loc[i, c] *= df1.loc[i, c]; df2
    Out[1145]: 
          y  z
    b   4.0  3
    c   NaN  4
    d  18.0  5
    e  28.0  6
    f   5.0  7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多