📌  相关文章
📜  如何将 Dataframe 列转换为 Python-Pandas 中的索引?

📅  最后修改于: 2022-05-13 01:55:09.587000             🧑  作者: Mango

如何将 Dataframe 列转换为 Python-Pandas 中的索引?

Pandas提供了一种方便的方式来处理数据及其转换。让我们看看如何在 Pandas 中将数据框列转换为行名或索引。
首先使用列表的字典创建一个数据框。

Python3
# 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


Python3
# 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


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


Python3
# 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


输出:

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

Python3

# 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

输出:

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

Python3

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

输出:


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

Python3

# 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

输出: