【问题标题】:Pandas enlargement of multidimensional objectsPandas 放大多维对象
【发布时间】:2017-07-09 12:52:42
【问题描述】:

我想向多维 pd.Series 添加行。

b = pd.Series([1,1,2,3], index = [["digit", "digit", "digit", "digit"], ["one", "one", "two", "three"]])

b
Out[30]: 
digit  one      1
       one      1
       two      2
       three    3
dtype: int64

现在,当我这样做时

b.loc["digit"].loc["four"] = 4

什么都没有发生。没有错误,但 b 保持不变。 虽然这种方法适用于一维系列

【问题讨论】:

    标签: python pandas multidimensional-array


    【解决方案1】:

    你需要sort_index,因为:

    PerformanceWarning:索引过去的 lexsort 深度可能会影响性能。

    然后使用loc进行元组:

    b = b.sort_index()
    b.loc[("digit", "four")] = 4
    print (b)
    digit  one      1
           one      1
           three    3
           two      2
           four     4
    dtype: int64
    

    concat 的另一个解决方案:

    c = pd.Series([4], index=pd.MultiIndex.from_arrays([['digit'],['four']]))
    b = pd.concat([b, c])
    print (b)
    digit  one      1
           one      1
           two      2
           three    3
           four     4
    dtype: int64
    

    【讨论】:

    • 非常感谢。它甚至在没有元组索引的情况下也能工作
    • hmm...问题是,当这些方法与 Serieses 一起使用时。但在数据框的情况下,我会得到额外的列而不是行
    • 是的,那么是必要的元组。 df.loc[("digit", "four"),:] = 4 用于所有列。 df.loc[("digit", "four"),'col'] = 4 为 cil 添加一个值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2021-10-02
    • 2020-02-23
    • 2015-12-30
    相关资源
    最近更新 更多