程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Pandas dataframe: row column conversion, one row generates multiple rows, and multiple rows merge into one row

編輯:Python

@ Founded in :2022.07.01
@ Modified to :2022.07.01

1、 Build a sample data

import pandas as pd
import numpy as np
df = pd.DataFrame({
' full name ': ['name_A', 'name_B', 'name_C'],
' class ': ['c1', 'c2', 'c2'],
' Chinese language and literature ': [90, 60, 70],
' mathematics ': [80, 98, 80],
' English ': [85, 90, 75],
' Physics ': [92, 63, 76],
' chemical ': [85,100, 89],
' biological ': [87, 91, 80]})

2、 One line generates multiple lines 【 Column turned 】

be used pandas Of melt Method .

# One row to many columns 
df_c = pd.melt(df, id_vars=[' full name ', ' class '], var_name=" subject ", value_name=" score ")
df_c

3、 Merge multiple lines into one 【 Transfer line column 】

pd.pivot(df_c, index=" full name ", columns=" subject ", values=" score ")
# rename_axis(index=, columns=) To rename the axis 
pd.pivot(df_c, index=" full name ", columns=" subject ", values=" score ").rename_axis(columns=None).reset_index()


The class was lost above , How to increase classes ?

pd.pivot(df_c, index=[" full name ", ' class '], columns=" subject ", values=" score ").rename_axis(columns=None).reset_index()

4、 Reference link

pandas Transfer line column 、 Column turned 、 And one row generates multiple rows
pandas How to perform elegant column to row conversion 、 Transfer line column ?
Pandas in Dataframe Transfer line column


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved