ely66
ely66

Reputation: 185

append dataframe columns inside a for loop

I want to append columns inside a dataframe one by one such that the data frame is inside a loop and with every loop iteration a columns append to the data frame

I tried the following, where range(len(correctors_indexes)) = 40 :

for i in range(len(correctors_indexes)):
    data = pd.DataFrame({'s_pos': s_pos})
    data['CXY' + str(i)] = closed_orbity
    data.to_csv("orm_y_CXY_hrm.csv")

But it only give as a result the s_pos and the last columns CXY39

I want to see result such that the s_pos and 39 other columns of the names: 'CXY' + str(i)

Upvotes: 0

Views: 47

Answers (1)

skowalak
skowalak

Reputation: 459

You have to define the DataFrame before the loop:

data = pd.DataFrame({'s_pos': s_pos})
for i in range(len(correctors_indexes)):
    data['CXY' + str(i)] = closed_orbity

data.to_csv("orm_y_CXY_hrm.csv")

Upvotes: 1

Related Questions