📜  Python|熊猫 dataframe.swapaxes()

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

Python|熊猫 dataframe.swapaxes()

Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。

Pandas dataframe.swapaxes()函数适当地交换轴和交换值轴。该函数将要交换的轴的名称作为参数。基于轴,它也会相应地更改数据。

示例 #1:使用swapaxes()函数交换数据框的轴。

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.DataFrame({"A":[10, 11, 7, 8, 5],
                   "B":[21, 5, 32, 4, 6],
                   "C":[11, 21, 23, 7, 9],
                   "D":[1, 5, 3, 8, 6]}, 
                   index =["A1", "A2", "A3", "A4", "A5"])
  
# Print the dataframe
df

# interchange the index and columns axis
df.swapaxes("index", "columns")

输出 :
示例 #2:使用swapaxes()函数将索引轴和列轴相互交换。数据框有一些缺失值。

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.DataFrame({"A":[1, 5 + 1j, 3+.2j, 4 + 1j, None],
                   "B":[3, 2, 4, 3, 4],
                   "C":["brook", "daniela", "samantha", "hayden", "nathan"],
                   "D":[None, 3, 6, None, 7]},
                   index =["A1", "A2", "A3", "A4", "A5"])
  
# Print the dataframe
df

# interchange the columns and index axis
  
df.swapaxes("index", "columns")

输出 :