【问题标题】:Pandas: how to set values in a dataframe specified by a loc (index and column) creating rows if index position doesn't exist?Pandas:如果索引位置不存在,如何在 loc(索引和列)指定的数据框中设置值创建行?
【发布时间】:2020-07-21 22:45:14
【问题描述】:

我有一个带有一些“空”(NaN)条目的数据框,例如

c = pd.DataFrame({"A":[1, 2, np.NAN, 4], "B":[11, 22, 33, np.NAN]}, index=["a", "b", "c", "d"])

     A     B
a  1.0  11.0
b  2.0  22.0
c  NaN  33.0
d  4.0   NaN

我想使用另外两个分别包含列 A 和 B 的值的数据框来“更新”,例如

a = pd.DataFrame({"A": [3, 4, 5, 6]}, index=["c", "d", "e", "f"])
b = pd.DataFrame({"B": [44, 55, 66]}, index=["d", "e", "f"])

获取更新版本:

     A     B
a  1.0  11.0
b  2.0  22.0
c  3.0  33.0
d  4.0  44.0
e  5.0  55.0
f  6.0  66.0

我尝试使用 .loc

c.loc[a.index, "A"] = ac.loc[a.index, "A"] = a.A

但是对于不在索引中的项目不断收到 KeyError。我还尝试了concat 的变体,但无法获得所需的输出。

是否有一个 pandas 函数可以在索引中已经存在时设置值,如果不存在则创建它们?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用两个combine_first

    df=b.combine_first(c).combine_first(a)
    Out[302]: 
         A     B
    a  1.0  11.0
    b  2.0  22.0
    c  3.0  33.0
    d  4.0  44.0
    e  5.0  55.0
    f  6.0  66.0
    

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2016-02-29
      • 2019-04-08
      • 2019-01-15
      • 2017-07-25
      相关资源
      最近更新 更多