Home >Backend Development >Python Tutorial >How Can Pandas\' `.explode()` Method Transform List-Based Columns into Separate Rows?

How Can Pandas\' `.explode()` Method Transform List-Based Columns into Separate Rows?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 20:25:111029browse

How Can Pandas' `.explode()` Method Transform List-Based Columns into Separate Rows?

Exploiting Pandas' .explode() Method to Unpack Lists into Rows

In Pandas, dealing with DataFrames containing columns of lists can be challenging when you want to have each list element represented as a separate row. This is where the .explode() method comes into play.

Pandas ≥ 0.25

For Pandas versions 0.25 and above, the game-changer is the .explode() method. It allows you to explode a list-like column into separate rows, thus converting it from its long form to a wide form.

import pandas as pd

# Sample DataFrame
df = pd.DataFrame({
    'trial_num': [1, 2, 3, 1, 2, 3],
    'subject': [1, 1, 1, 2, 2, 2],
    'samples': [list(np.random.randn(3).round(2)) for i in range(6)]
})

# Explode using .explode()
exploded_df = df.explode('samples')

# Reset index to be monotonically increasing (optional)
exploded_df = exploded_df.reset_index(drop=True)

print(exploded_df)

# Output:
#    subject  trial_num  sample
# 0        1          1    0.57
# 1        1          1   -0.83
# 2        1          1    1.44
# 3        1          2   -0.01
# 4        1          2    1.13
# 5        1          2    0.36
# 6        1          3    1.18
# 7        2          1   -0.08
# 8        2          1   -4.22
# 9        2          1   -2.05
# 10       2          2    0.72
# 11       2          2    0.79
# 12       2          2    0.53
# 13       2          3    0.4
# 14       2          3   -0.32
# 15       2          3   -0.13

Note that .explode() operates on a single column at a time. For columns containing mixed types (e.g., lists and scalars), .explode() behaves sensibly and preserves empty lists and NaNs.

The above is the detailed content of How Can Pandas\' `.explode()` Method Transform List-Based Columns into Separate Rows?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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