Home  >  Article  >  Backend Development  >  How to efficiently implement column to row operations in Python

How to efficiently implement column to row operations in Python

王林
王林forward
2023-04-26 23:49:061895browse

The data source is roughly like this:

How to efficiently implement column to row operations in Python

Based on this, I came up with an idea: see how to quickly implement this operation in Python.

The data source has been constructed, let’s get started!

import pandas as pd

df = pd.read_excel("分列转到行.xlsx",header=None)
df.columns = ["年级","姓名"]
df

The results are as follows:

How to efficiently implement column to row operations in Python

The whole code is very simple, take a look if you don’t believe it!

df["新列"] = df["姓名"].str.split(";")
df["新列"]

The results are as follows:

How to efficiently implement column to row operations in Python

Finally add an explosion function and win it directly!

df1 = df.explode("新列")
df1

Some screenshots are as follows:

How to efficiently implement column to row operations in Python

How should you restore this data for the df1 obtained above?

def func(df):
    return ','.join(df.values) #这里改为什么分隔符,随你自己!
df2 = df1.groupby(by='年级').agg(func).reset_index()
df2

The results are as follows:

How to efficiently implement column to row operations in Python

The above is the detailed content of How to efficiently implement column to row operations in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete