【问题标题】:is it possible to add an index in between two indexes of dataframe [duplicate]是否可以在数据框的两个索引之间添加索引[重复]
【发布时间】:2020-02-19 09:00:32
【问题描述】:
import pandas as pd

df = pd.DataFrame({'Age': [30, 40, 30, 40, 30, 30, 20, 25],
                   'Height': [120, 162, 120, 120, 120, 72, 120, 81]})
modDfObj = df.append({'Age' : 25, 'Height':172,} , ignore_index=True) 

modDfObj

"""是否可以在两行之间添加一行,是否可以在两个索引之间再添加一个索引"""

【问题讨论】:

  • 你能添加预期的输出吗?
  • 嗨@jezrael 这不是完美的答案,这个解决方案正在替换索引值,但我想添加新值而不替换旧值
  • 所以使用pd.concat([df.iloc[:2], line, df.iloc[3:]], ignore_index=True)
  • 这个也替换了索引值
  • 明白了,df2 = pd.concat([df.iloc[:3], line, df.iloc[3:]]).reset_index(drop=True), "df.iloc [3:]]).reset_index(drop=True)" 这个,放行之后,reset_index()应该在那里

标签: python pandas dataframe


【解决方案1】:
import pandas as pd

df = pd.DataFrame({'Age': [30, 40, 30, 40, 30, 30, 20, 25],
                   'Height': [120, 162, 120, 120, 120, 72, 120, 81]},
                  index=['Jane', 'Jane', 'Aaron', 'Penelope', 'Jaane', 'Nicky',
                         'Armour', 'Ponting'])
line = pd.DataFrame({"Age": 33, "Height": 130}, index=[2])
df2 = pd.concat([df.iloc[:2], line, df.iloc[2:]]).reset_index(drop=True)
df2

"""得到了预期的输出"""

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2018-09-04
    • 2013-10-16
    • 2020-12-30
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多