lapgoch
lapgoch

Reputation: 35

Looping and append to dataframe with column names in Pyhton

I had this challenge of looping through and appending to a data frame in 2 separate columns. I would like the result of col1 and col2 to be appended to the data frame under the columns 'col1' & 'col2'.

What i have so far is the below:

result = pd.DataFrame(columns = ['col1', 'col2'])
for i in range(5):
    col1 = i + 1
    col2 = i + 100
    result.append(pd.concat([str(col1), col2]))

Which outputs:

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

My desired output is:

col1 col2
1 101
2 102
3 103
4 104
5 105

Upvotes: 0

Views: 1222

Answers (1)

Raymond Kwok
Raymond Kwok

Reputation: 2541

If using append here is necessary, you may do

result = pd.DataFrame(columns = ['col1', 'col2'])
for i in range(5):
    col1 = i + 1
    col2 = i + 100
    result = result.append({'col1': str(col1), 'col2': col2}, ignore_index=True)

Otherwise, with concat

result = pd.concat([
    pd.Series({'col1': str(i + 1), 'col2': i + 100})
        for i in range(5)
], axis=1).transpose()

Or I would do this

result = pd.DataFrame({
    'col1': list(map(str, range(1, 6))),
    'col2': list(range(100, 105)),
})

Upvotes: 1

Related Questions