如何将具有多词名称的行添加到 pandas 数据框
How to add a row with a multi-word name to a pandas dataframe
我在 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
.
如有任何帮助,我们将不胜感激!谢谢!!!
使用变量 s
追加 Series
,此处 np.array
在 Series
构造函数中不是必需的:
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)
我在 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
.
如有任何帮助,我们将不胜感激!谢谢!!!
使用变量 s
追加 Series
,此处 np.array
在 Series
构造函数中不是必需的:
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)