I have a data frame which has a (3,1) df-shape like this:-
My Dataframe:
KDB 0 2 1 7 2 9
And I have a NumPy array that looks like this
My Numpy Array:
[[40],[50],[60]]
I want to append the value of a specific index in the array to my data frame. Let's say I want to add "60" to my data frame. So, I want my data frame to look like this.
My New Dataframe:
KDB 0 2 1 7 2 9 3 60
I wrote a code, but it didn't work.
new_df = my_df.append(pd.Series(my_array[2][0]), ignore_index=True)
Python throws this error "non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,2)"
Can someone please help me understand what am I doing wrong?
Thank you so much!
Your code did not cause any error, but my DataFrame has:
But the result is wrong, as it contains 2 columns.
To get the proper result, use the following code:
my_df.append(pd.Series(my_array[2], index=['KDB']), ignore_index=True)
The trick is to specify the column name as the index in the temporary Series , so the value of interest is added to the right column.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.