Christopher Jenkins
Christopher Jenkins

Reputation: 875

Build pandas dataframe in for loop

I have a for loop that iterates over a dataframe and calculates two pieces of information:

for id in members['id']
    x = random_number_function()
    y = random_number_function()

I'd like to store id, x and y in a dataframe that is built one row at a time, for each pass through the for loop.

Upvotes: 1

Views: 6862

Answers (1)

iayork
iayork

Reputation: 6699

Here's an example of using a dict to build a dataframe:

dict_for_df = {}
for i in ('a','b','c','d'):    # Don't use "id" as a counter; it's a python function
    x = random.random()        # first value
    y = random.random()        # second value
    dict_for_df[i] = [x,y]     # store in a dict
df = pd.DataFrame(dict_for_df) # after the loop convert the dict to a dataframe

Upvotes: 4

Related Questions