【问题标题】:How to add a row with a multi-word name to a pandas dataframe如何将具有多字名称的行添加到熊猫数据框中
【发布时间】:2021-09-19 13:34:44
【问题描述】:

我在 pandas 中有一个数据框(称为 df),我想在其中添加一行(称为 'Row 5')。但是该行的名称不止一个词。那我该怎么做呢?

这是df

这是我尝试过的代码,但正如您将看到的,它最终会出错。

sum_part = 37 + 55 + 11 + 21
product_part = 37 * 55 * 11 * 21

pd.Series(
    np.array([37, 55, 11, 21, sum_part, product_part]),
    index=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Sum', 'Product'],
    name='Row 5')

df = df.append('Row 5')

这段代码导致的具体错误是:TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

对此的任何帮助将不胜感激!谢谢!!!

【问题讨论】:

    标签: python pandas dataframe row typeerror


    【解决方案1】:

    使用变量s 追加Series,这里np.arraySeries 构造函数中不是必需的:

    s = pd.Series([37, 55, 11, 21, sum_part, product_part],
                  index=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Sum', 'Product'],
                  name='Row 5')
    

    或者可以将列名传递给index参数:

    s = pd.Series([37, 55, 11, 21, sum_part, product_part],
                  index=df.columns,
                  name='Row 5')
    

    df = df.append(s)
    

    【讨论】:

    • 尽管没有必要,我还是喜欢使用 numpy 数组,只是因为它们的所有好处。另外,感谢df.columns 的有用提示。
    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2018-01-21
    相关资源
    最近更新 更多