0

I'm trying to create an empty pandas DataFrame with the columns ['ImageName','faces','ImageWidth', 'ImageHeight'] to which I'm trying to append a row. Let's take the following row as an example: ['selfie_10.png',3,200,300].

So far, I've come up with the following code snippet. But either it doesn't work or it throws an error.

import pandas as pd

columns = ['ImageName','faces','ImageWidth', 'ImageHeight']

df = pd.DataFrame(columns=columns)

for i in range(0,10):
    row = ['selfie_10.png',3,200,300]
    df.append(row,ignore_index=True)
 
print(df)

The output is unfortunately an empty array.

In [72]:runfile('/Users/add_row.py', wdir='/Users/Desktop/faces')
Empty DataFrame
Columns: [ImageName, faces, ImageWidth, ImageHeight]
Index: []

Can anybody help me?

1
  • 1
    try df.loc[i] = row in the for loop instead of appending. Commented Feb 28, 2021 at 9:19

2 Answers 2

2

First of all, create a list and append all the rows into that list then convert that list into a DataFrame.

import pandas as pd
columns = ['ImageName','faces','ImageWidth', 'ImageHeight']
a = []
for i in range(0,10):
    row = ['selfie_10.png',3,200,300]
    a.append(row)
df = pd.DataFrame(a,columns=columns)
Sign up to request clarification or add additional context in comments.

Comments

1

Thanks to @MustafyAydin I've come up with this solution.

columns = ['ImageName','faces','ImageWidth', 'ImageHeight']

df = pd.DataFrame(columns=columns)
print(df.shape)

for i in range(0,10):
    row = ['selfie_10.png',3,200,300]
    index = df.shape[0] + 1
    df.loc[index] = row
 
print(df)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.