Pandas split column of lists into multiple columns

后端 未结 8 1657
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:28

I have a pandas DataFrame with one column:

import pandas as pd

df = pd.DataFrame(
    data={
        \"teams\": [
            


        
相关标签:
8条回答
  • 2020-11-21 07:20

    This solution preserves the index of the df2 DataFrame, unlike any solution that uses tolist():

    df3 = df2.teams.apply(pd.Series)
    df3.columns = ['team1', 'team2']
    

    Here's the result:

      team1 team2
    0    SF   NYG
    1    SF   NYG
    2    SF   NYG
    3    SF   NYG
    4    SF   NYG
    5    SF   NYG
    6    SF   NYG
    
    0 讨论(0)
  • 2020-11-21 07:29

    Much simpler solution:

    pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])
    

    Yields,

      team1 team2
    -------------
    0    SF   NYG
    1    SF   NYG
    2    SF   NYG
    3    SF   NYG
    4    SF   NYG
    5    SF   NYG
    6    SF   NYG
    7    SF   NYG
    

    If you wanted to split a column of delimited strings rather than lists, you could similarly do:

    pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
                 columns=['team1', 'team2'])
    
    0 讨论(0)
提交回复
热议问题