I have a dataframe in pandas (called df
) and I would like to add a row (called 'Row 5'
) to it. But the row's name has more than one word. So how would I do this?
This is df
This is the code that I tried, but, as you will read, it ends up in an error.
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')
The specific error that this code causes is: TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid
.
Any help on this would be greatly appreciated! Thank you!!!
Use variable s
for append Series
, here np.array
is not necessary in Series
constructor:
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')
Or is possible pass columns names to index
parameter:
s = pd.Series([37, 55, 11, 21, sum_part, product_part],
index=df.columns,
name='Row 5')
df = df.append(s)