【问题标题】:append to/insert a row with an index value into an indexed dataframe without losing the index name?在不丢失索引名称的情况下将具有索引值的行追加/插入到索引数据框中?
【发布时间】:2021-11-13 05:53:48
【问题描述】:

给定数据框:

df = pd.DataFrame([{'myindex':1,'a':2,'b':3},{'myindex':2,'a':22,'b':33}]).set_index('myindex')

还有一个新行:

new_row = {'myindex':11,'a':20,'b':30}

new_row添加到数据帧到reset索引,append没有myindex作为索引,然后用set_index重新索引到myindex,是最简洁的方法吗?

df = df.reset_index().append(new_row,ignore_index=True).set_index('myindex')

我尝试了pandas 方法concat,但它消除了index name,同时添加了一个名为myindex 的新列,除了new_row 之外的所有内容都包含NaN。我试着做一个:

new_row_myindex = new_row['myindex']
del new_row['myindex']
df = pd.concat([df, pd.DataFrame(new_row,index=[new_row_myindex])])

但这会删除索引的名称myindex

我尝试了DataFrame 方法insert,但在类似的方法中是独一无二的,它没有axis 参数,因此仅限于插入列(想想就很好奇)。

【问题讨论】:

  • 可能像df.loc[11] = {'a': 20, 'b': 30} 这样的东西是标准方法。 (当然,可以从dict 完成一些程序化的参数解包)
  • 如果一个人有许多这样的字典要追加/插入,那是否会在一个循环中保持标准方法?
  • 没有ignore_index的情况下,不构建一个单独的相同结构的DataFrame并追加一次:df = df.append(pd.DataFrame([{'myindex':11,'a':20,'b':30}, {'myindex':12,'a':20,'b':30}]).set_index('myindex'))
  • 单行方法需要像我在问题中描述的那样执行del 操作,以免收到错误:ValueError: Length of values (3) does not match length of index (2)。这再次引发了 DataFrame 方法 insertaxis 参数的神秘缺失。但至少我得到了答案。谢谢!
  • 新行字典中的第一个(键,值)对总是myindex吗?

标签: pandas indexing


【解决方案1】:

你可以试试这样的:

df = df.append((pd.Series({'myindex':11,'a':20,'b':30}, name=new_row['myindex'])[1:]))

# Output
          a     b
myindex         
1         2     3
2        22     33
11       20     30

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2019-06-24
    • 2019-05-28
    相关资源
    最近更新 更多