在Pandas中把列名转换成行名/索引

在Pandas中把列名转换成行名/索引

Pandas提供了一种方便的方式来处理数据和它的转换。让我们看看如何在Pandas中把一个列转换成行名/索引。

首先创建一个数据框架,其中有列表的数据。

# importing pandas as pd
import pandas as pd
 
# Creating a dict of lists
data = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"],
       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],
       'Score':["80","90","60", "30", "50"],
       'Result': ["Pass","Pass","Pass","Fail","Fail"]}
 
# creating a dataframe
df = pd.DataFrame(data)
  
df

输出:

在Pandas中把列名转换成行名/索引

方法#1:使用set_index()方法。

# importing pandas as pd
import pandas as pd
 
# Creating a dict of lists
data = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"],
       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],
       'Score':["80","90","60", "30", "50"],
       'Result': ["Pass","Pass","Pass","Fail","Fail"]}
 
# Creating a dataframe
df = pd.DataFrame(data)
 
# Using set_index() method on 'Name' column
df = df.set_index('Name')
 
df

输出:

在Pandas中把列名转换成行名/索引

现在,将索引名称设为无。

# set the index to 'None' via its name property
df.index.names = [None]
 
df

输出:

在Pandas中把列名转换成行名/索引

方法#2:使用pivot()方法。
为了将数据框架中的列转换成行名/索引,Pandas有一个内置函数Pivot。
现在,假设我们希望Result是数据框架中的行/索引,列是名称,为了实现这个目标,pandas提供了一个名为Pivot的方法。让我们看看它是如何工作的。

# importing pandas as pd
import pandas as pd
 
# Creating a dict of lists
data = {'name':["Akash", "Geeku", "Pankaj", "Sumitra", "Ramlal"],
       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],
       'Score':["80", "90", "60", "30", "50"],
       'Result': ["Pass", "Pass", "Pass", "Fail", "Fail"]}
 
df = pd.DataFrame(data)
 
# pivoting the dataframe
df.pivot(index ='Result', columns ='name')
 
df

输出:

在Pandas中把列名转换成行名/索引

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程