【问题标题】:Pandas append row without specifying columns熊猫追加行而不指定列
【发布时间】:2023-02-26 16:47:02
【问题描述】:

我想向数据框添加或附加一行(以列表的形式)。所有方法都要求我首先将列表转换为另一个数据框,例如。

df = df.append(another dataframe)
df = df.merge(another dataframe)
df = pd.concat(df, another dataframe)

如果索引在 https://www.statology.org/pandas-add-row-to-dataframe/ 的运行编号中,我发现了一个技巧

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18],
                   'rebounds': [7, 7, 8, 13, 7, 4],
                   'assists': [11, 8, 10, 6, 6, 5]})

#view DataFrame
df

    points  rebounds assists
0   10  7    11
1   12  7    8
2   12  8    10
3   14  13   6
4   13  7    6
5   18  4    5

#add new row to end of DataFrame
df.loc[len(df.index)] = [20, 7, 5]

#view updated DataFrame
df

        points  rebounds assists
0   10  7    11
1   12  7    8
2   12  8    10
3   14  13   6
4   13  7    6
5   18  4    5
6   20  7    5

但是,数据框必须在运行编号中有索引,否则,添加/追加将覆盖现有数据。

所以我的问题是:是否有简单、万无一失的方法来将列表附加/添加到数据框?

非常感谢 !!!

【问题讨论】:

    标签: pandas


    【解决方案1】:
    >>> df
      points rebounds assists
    3     10        7      11
    1     12        7       8
    2     12        8      10
    

    如果索引是“数字”——您可以将 1 添加到最大索引。

    >>> df.loc[max(df.index) + 1] = 'my', 'new', 'row'
    >>> df
      points rebounds assists
    3     10        7      11
    1     12        7       8
    2     12        8      10
    4     my      new     row
    

    【讨论】:

    • 谢谢。我已经接受了答案。我想如果索引不是数字,它会有一些意义,我将不得不插入一些有意义的东西。
    猜你喜欢
    • 2016-09-13
    • 2015-09-20
    • 2015-01-02
    • 2021-10-26
    • 1970-01-01
    • 2016-07-21
    • 2018-04-30
    • 2016-01-13
    • 1970-01-01
    相关资源
    最近更新 更多