Sanwal
Sanwal

Reputation: 307

How to Append data in While loop into Empty DataFrame

I have dataframe which has 5 columns.

Df = pd.DataFrame(columns=['userId','movieId','rating','timestamp','genres'])

I have this function

def Main():

    flag = 0
    while(flag <=99):
        data1 = pickRandomMovies()
        data2 = usersToMovies(data1)
        if len(data2) < 6:
            data2 = data1
        else:
            flag +=1
            data3 = commonUsers(data2)
            #append all values of data3 here to new dataframe
            df_new.append(data3)

            findingRatings(data3)
>>data3
userId  movieId  rating   timestamp                      genres
 27       60      3.0     962685387         Adventure|Children|Fantasy
 103      60      4.0     1431968436        Adventure|Children|Fantasy
 160      60      2.0     971619579         Adventure|Children|Fantasy
 27      1210     4.0     962684909         Action|Adventure|Sci-Fi
 103     1210     3.5     1431957028        Action|Adventure|Sci-Fi
 160     1210     5.0     971113953         Action|Adventure|Sci-Fi

i want to append all values of data3 into new dataframe in every iteration.

Upvotes: 2

Views: 537

Answers (1)

ArunJose
ArunJose

Reputation: 2159

change your code to

def Main():

    flag = 0
    while(flag <=99):
        data1 = pickRandomMovies()
        data2 = usersToMovies(data1)
        if len(data2) < 6:
            data2 = data1
        else:
            flag +=1
            data3 = commonUsers(data2)
            #append all values of data3 here to new dataframe
            df_new=df_new.append(data3)

            findingRatings(data3)

df_new.append(data3) only appends the value it does not assign the value it should be done explicitly by df_new=df_new.append(data3)

Upvotes: 1

Related Questions