【问题标题】:Adding values to end of pandas data frame from beginning of data frame [duplicate]从数据框的开头向熊猫数据框的末尾添加值[重复]
【发布时间】:2018-05-10 01:51:10
【问题描述】:

我有一个看起来像这样的 pandas 数据框:

  A B C
0 1 2 3
1 4 5 6
2 7 8 9

我想将第 0 行添加到数据框的末尾,并获得一个如下所示的新数据框:

  A B C
0 1 2 3
1 4 5 6
2 7 8 9
3 1 2 3

我可以在 pandas 中做些什么来做到这一点?

【问题讨论】:

  • df.append(df.iloc[0])?
  • df.loc[len(df)] = df.iloc[0]

标签: python pandas dataframe append concat


【解决方案1】:

你可以试试:

df = df.append(df.iloc[0], ignore_index=True)

【讨论】:

    【解决方案2】:

    如果您从列表中插入数据,这可能会有所帮助 -

    import pandas as pd
    
    df = pd.DataFrame( [ [1,2,3], [2,5,7], [7,8,9]], columns=['A', 'B', 'C'])
    
    print(df)
    df.loc[-1] = [1,2,3] # list you want to insert
    df.index = df.index + 1  # shifting index
    df = df.sort_index()  # sorting by index
    print(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2019-11-12
      • 2019-06-22
      • 2017-02-11
      • 1970-01-01
      • 2021-06-11
      相关资源
      最近更新 更多