简体   繁体   中英

How to replace values inside DataFrame columns with data from a python list?

as the title says, how do I replace the values in a DataFrame column?

Here is a tiny bit from my data frame:

import pandas as pd

outdated_list = pd.DataFrame({"country": ['Afghanistan', "Albania", "Algeria"], "cases": ["No data", "No data", "No data"],
                   "deaths": ["No data", "No data", "No data"], "recov": ["No data", "No data", "No data"],
                   "flag_scr": ["No data", "No data", "No data"]})

Output

       country    cases   deaths    recov flag_scr
0  Afghanistan  No data  No data  No data  No data
1      Albania  No data  No data  No data  No data
2      Algeria  No data  No data  No data  No data

And here is the list, which has the data I want to put inside the right columns:

updated_list = [['Afghanistan', '40,141', '1,488', '33,561',
                 '//upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Flag_of_Afghanistan.svg/720px-Flag_of_Afghanistan.svg.png'],
                ['Albania', '16,774', '448', '10,001',
                 '//upload.wikimedia.org/wikipedia/commons/thumb/3/36/Flag_of_Albania.svg/21px-Flag_of_Albania.svg.png'],
                ['Algeria', '54,203', '1,846', '37,971',
                 '//upload.wikimedia.org/wikipedia/commons/thumb/7/77/Flag_of_Algeria.svg/720px-Flag_of_Algeria.svg.png']]

So to clarify, I want to replace for eg. the Cases value in Afghanistan row with value 40,141 from the list. How do I do it? I guess it would be best to do it with a loop, because in the original code the list is much longer and not sorted as in the example.

You can create a dataframe directly from your list. You'll need to give it column names though.

updated_df = pd.DataFrame(updated_list, columns=outdated_list.columns)

If you want to actually update your original dataframe, as in the case if there is incomplete or extra data in your list, you can use the update method for dataframes.

outdated_list.update(updated_df)

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