Home > Software design >  Add new columns to a dataframe in for loop
Add new columns to a dataframe in for loop

Time:11-03

I am able to write a for loop that adds a row to a dataframe each time as with the following example:

from random import randint
import numpy as np
dataframe = []
for i in range(2):
value = randint(0,10)
for j in range(2):
    mean = np.mean(value)
    dataframe.append(mean)
    cols=['mean']
    result=pd.DataFrame(dataframe, columns = cols)
result

This outputs a dataframe that looks like:

mean
8
8
9
9

How could I output a dataframe that looks like

mean_1 mean_2 mean_3 mean_4
8      8      9      9

CodePudding user response:

import pandas as pd
from random import randint
import numpy as np

m = 2
n = 2

dataframe = pd.DataFrame([0], columns = ['mean_1'])
for i in range(m):
    value = randint(0,10)
    for j in range(n):
        mean = np.mean(value)
        dataframe['mean_' str(n*i j 1)] = mean

CodePudding user response:

from random import randint
import numpy as np
import pandas as pd
dataframe = []
count = 1
cols = []
for i in range(2):
    value = randint(0,10)
    for j in range(2):
        mean = np.mean(value)
        dataframe.append(mean)
        cols.append('mean_' str(count))
        count = count   1
df=pd.DataFrame(columns=cols)
a_series = pd.Series(dataframe, index = cols)
d = df.append(a_series, ignore_index=True)

Output: enter image description here

  • Related