Home > Backend Development > Python Tutorial > How to Split a Pandas Column of Lists into Multiple Columns?

How to Split a Pandas Column of Lists into Multiple Columns?

Patricia Arquette
Release: 2024-12-19 18:02:10
Original
284 people have browsed it

How to Split a Pandas Column of Lists into Multiple Columns?

Splitting Pandas Column of Lists into Multiple Columns

Problem

Consider a Pandas DataFrame with a column containing lists:

import pandas as pd

df = pd.DataFrame({"teams": [[["SF", "NYG"]] for _ in range(7)]})

       teams
0  [[SF, NYG]]
1  [[SF, NYG]]
2  [[SF, NYG]]
3  [[SF, NYG]]
4  [[SF, NYG]]
5  [[SF, NYG]]
6  [[SF, NYG]]
Copy after login

To transform this column into two individual columns, follow the below steps:

Solution

  1. Create List of Values Using to_list():
import pandas as pd

d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
print (df2)
       teams
0  [SF, NYG]
1  [SF, NYG]
2  [SF, NYG]
3  [SF, NYG]
4  [SF, NYG]
5  [SF, NYG]
6  [SF, NYG]
Copy after login
  1. Extract Columns Using Assignment:

Assign a new DataFrame with the desired columns:

df2[['team1','team2']] = pd.DataFrame(df2.teams.tolist(), index= df2.index)
print (df2)
       teams team1 team2
0  [SF, NYG]    SF   NYG
1  [SF, NYG]    SF   NYG
2  [SF, NYG]    SF   NYG
3  [SF, NYG]    SF   NYG
4  [SF, NYG]    SF   NYG
5  [SF, NYG]    SF   NYG
6  [SF, NYG]    SF   NYG
Copy after login
  1. Create New DataFrame for Result:

Alternatively, a new DataFrame can be created separately:

df3 = pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
print (df3)
  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
Copy after login

Note: Using apply(pd.Series) for this operation can be significantly slower than the methods described above.

The above is the detailed content of How to Split a Pandas Column of Lists into Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template