简体   繁体   中英

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

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]

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM