Search code examples
pythonpandastuples

From tuples to multiple columns in pandas


How do I convert this dataframe

                                          location  value                       
0                   (Richmond, Virginia, nan, USA)    100                       
1              (New York City, New York, nan, USA)    200                       

to this:

    city            state       region    country   value
0   Richmond        Virginia    nan       USA       100
1   New York City   New York    nan       USA       200

Note that the location column in the first dataframe contains tuples. I want to create four columns out of the location column.


Solution

  • new_col_list = ['city','state','regions','country']
    for n,col in enumerate(new_col_list):
        df[col] = df['location'].apply(lambda location: location[n])
    
    df = df.drop('location',axis=1)