Home > Mobile >  How can I insert values from a list to DataFrame columns?
How can I insert values from a list to DataFrame columns?

Time:02-17

I need to insert values from a list to corresponding column in a df (first value to first column, second value to second column etc.), but unable to do it. Using the next code values paste only to rows, not it columns.

list1 = pd.Series(list1) 
pd.concat([df_sum, list1])

df_sum.append(list1) gives the same result. So any suggestions?

Code for example:

df_sum = pd.DataFrame(columns = ['russian language', 'english language', 'mathemathics', 'geometry', 'algebra', 'computer science', 'history',
                                 'geography', 'biology', 'social science', 'chemistry', 'physics'])
list1 = [28323,
 29302,
 9570,
 22014,
 18359,
 20514,
 25139,
 24678,
 23215,
 20640,
 19904,
 21494]

CodePudding user response:

You can achieve that by using list and loc

to_append = list(list1)
df_length = len(df_sum)
df_sum.loc[df_length] = to_append
pd.DataFrame(data=df_sum)

CodePudding user response:

For a quick answer: I would use a dictionary to compile by index

dict_temp = {}
for i, col in enumerate(df_sum.columns.values):
 dict_temp[col] = [list1[i]]

pd.DataFrame.from_dict(dict_temp)

or do it like that. But depends on your future purposes. I guess you want to add more lists at some point?

for i, col in enumerate(df_sum.columns.values):
 df_sum.at[0, col] = list1[i]

But there might be a better solution

  • Related