How to efficiently implement column to row operations in Python

王林
Release: 2023-04-26 23:49:06
forward
1938 people have browsed it

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
Copy after login

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["新列"]
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template