user11555039
user11555039

Reputation:

Appending a row to a pandas dataframe

I have the following code:

def randFunc(data,x,y,w,h,n): #(this has problems)
    df = pd.DataFrame({"X":[], 
                         "Y":[]}) 
    for i in range(n):
        for j in range(n):
            data1 = filterbox(data,x,y,w,h,i,j,n)
            if data1.empty:
                data1 = data1.sample()
                print(data1)
                df.append(data1)
            else:
                sus = data1.sample()
                df.append(sus)
    return df
    """gets a list of random points in each subinterval in a list"""

For data1 is a row from a dataframe, so is sus. For some reason, however, when I append to df, no new values show up in df. Why is this and how can I fix it? Thanks

Upvotes: 0

Views: 57

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114068

DataFrame.append returns a new dataframe

import pandas as pd

df = pd.DataFrame([[1,2,3]])
# you probably want to ignore_index so that you have unique indexes
df2 = df.append([[4,5,6]],ignore_index=True)
print("DF is unchanged:")
print(df)

print("DF2 has the new DataFrame:")
print(df2)

#this is just a convience wrapper for pandas.concat
df3 = pd.concat([df2,[[4,4,4]]],ignore_index=True)
print("DF3")
print(df3)

Upvotes: 1

Related Questions