【问题标题】:insert multiple rows in to data frame based on index position根据索引位置将多行插入数据框
【发布时间】:2021-08-08 18:13:45
【问题描述】:

我有两个多级索引数据框,如下所示。我需要将它们合并在一起。 具体来说,我需要根据匹配的索引将 df2 中的行插入到 df1 中 - 在级别的末尾。下面的数据可以告诉你我的意思,预期的输出也在那里。它需要是“程序化的并且可以运行这些实例的负载!非常感谢提前

数据


array1 = [["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"]]
tupples1 = list(zip(*array1))
index1 = pd.MultiIndex.from_tuples(tupples1, names=["first"])
df1 = pd.DataFrame(np.random.randn(8), index=index1)#
df1.reset_index(inplace=True)


array2 = [["bar", "bar","bar","qux","qux","qux","qux"]]
tupples2 = list(zip(*array2))
index2 = pd.MultiIndex.from_tuples(tupples2, names=["first"])
df2 = pd.DataFrame(np.random.randn(7), index=index2)
df2.reset_index(inplace=True)

预期输出将是这种形状(但具有实际值)

array3 = [["bar", "bar","bar", "bar","bar", "baz", "baz", "foo", "foo", "qux", "qux","qux","qux","qux","qux","qux"]]
tupples3 = list(zip(*array3))
index3 = pd.MultiIndex.from_tuples(tupples3, names=["first"])
df3 = pd.DataFrame(np.random.randn(16), index=index3)
df3.reset_index(inplace=True)

【问题讨论】:

  • 在你的例子中,你最终得到了重复的索引(例如(bar,one)),在真实数据中是一样的吗?
  • 嗨@Ben.T 感谢您的评论!是的,我确实希望重复(实际上应该发生的是 df2 中的一个栏应该完全替换原始栏,df2 中的一个 - 但是为了进行完整性检查,我将在插入新行后将其删除,但也许效率不高。)
  • 是的,我相信你的想法让它变得更加复杂。我的理解是,在确保 df1 已经是 reindex 之后使用 update 并在 df1 和 df2 之间使用 index.union 应该做你想做的事。索引顺序重要吗?
  • 感谢您的指导。索引顺序确实很重要,是的,df1 中的索引顺序必须与 df2 中的相同
  • @Ben.T 抱歉,您介意告诉我您的意思吗?我正在尝试关注,但在重新索引/更新时无法解决“ValueError:无法从重复轴重新索引”问题。之后似乎没有联合属性

标签: python pandas indexing insert multi-level


【解决方案1】:

这是在第一个索引级别上使用pd.factorize 的一种方法,一旦您concat 两个数据帧,就可以获得该级别的某种顺序。

np.random.seed(1)
df3 = pd.concat([df1, df2])

df3 = (
    df3.set_index( # add two index level for sorting
         [list(range(len(df3))), # to have current order of rows
          pd.factorize(df3.index.get_level_values('first'))[0]], # to have order of first index 
         append=True) # to not replace original index
       .sort_index(level=[-1, -2]) # sort as wanted
       .droplevel([-2,-1]) # delete the extra index
)
print(df3)
                     0
first second          
bar   one     1.624345
      two    -0.611756
      one     0.319039
      two    -0.249370
      three   1.462108
baz   one    -0.528172
      two    -1.072969
foo   one     0.865408
      two    -2.301539
qux   one     1.744812
      two    -0.761207
      one    -2.060141
      two    -0.322417
      three  -0.384054
      four    1.133769

请注意,您可以执行相同的操作,将用于排序的两个级别添加为列并使用sort_values

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2015-06-12
    相关资源
    最近更新 更多