Ben10
Ben10

Reputation: 297

Add many 1-D array to dataframe as a row?

I am new to python and I want to know how to add many 1-D array to dataframe as a row. I have look into the previous question here but it is a bit different in my case. Here is the code:

df = pd.DataFrame(columns=['Col1', 'Col2', 'Col3'])
arr = np.empty(3)
arr[0] = 756
arr[1] = 123
arr[2] = 452

let's say this answer work well:

df.append(pd.DataFrame(arr.reshape(1,-1), columns=list(df)), ignore_index=True)

But when I wanted to add another 1-D array in the same dataframe:

a = np.empty(3)
a[0] = 700
a[1] = 100
a[2] = 400
df.append(pd.DataFrame(a.reshape(1,-1), columns=list(df)), ignore_index=True)

I got the empty dataframe. What wrong with it? How can I add many 1-D array in general? Any help would be much appreciated!

My desire output:

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
|  756 |  123 |  452 |
+------+------+------+
|  700 |  100 |  400 |
+------+------+------+

Upvotes: 0

Views: 195

Answers (1)

Jan Alexander
Jan Alexander

Reputation: 165

You need to reassign df:

this:

df = df.append(pd.DataFrame(arr.reshape(1,-1), 
                            columns=list(df)), ignore_index=True)

The complete code then becomes:

import pandas as pd
import numpy as np

df = pd.DataFrame(columns=['Col1', 'Col2', 'Col3'])
arr = np.empty(3)
arr[0] = 756
arr[1] = 123
arr[2] = 452
df = df.append(pd.DataFrame(arr.reshape(1, -1),
                            columns=list(df)), ignore_index=True)
a = np.empty(3)
a[0] = 700
a[1] = 100
a[2] = 400
df = df.append(pd.DataFrame(a.reshape(1, -1),
                            columns=list(df)), ignore_index=True)
print('Result: ')
print(df)

# A bit more efficient though:
arr = np.empty((2, 3))
arr[0, 0] = 756
arr[0, 1] = 123
arr[0, 2] = 452

arr[1, 0] = 700
arr[1, 1] = 100
arr[1, 2] = 400

df_2 = pd.DataFrame(columns=['Col1', 'Col2', 'Col3'], data=arr)
print('\nSame result, but more efficient : ')
print(df_2)

Upvotes: 1

Related Questions