📜  Python|熊猫 dataframe.melt()

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

Python|熊猫 dataframe.melt()

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

Pandas dataframe.melt dataframe.melt()函数将 DataFrame 从宽格式转换为长格式,可选择保留标识符变量集。此函数可用于将 DataFrame 消息发送到其中一个或多个列是标识符变量 (id_vars) 的格式,而所有其他列,被认为是测量变量 (value_vars),都“不旋转”到行轴,只留下两个非标识符列,“变量”和“值”。

示例 #1:使用melt()函数将“A”列设置为标识符变量,将“B”列设置为值变量。

Python3
# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.DataFrame({"A":[12, 4, 5, 44, 1], 
                   "B":[5, 2, 54, 3, 2], 
                   "C":[20, 16, 7, 3, 8], 
                   "D":[14, 3, 17, 2, 6]})
  
# Print the dataframe
df


Python3
# function to unpivot the dataframe
df.melt(id_vars =['A'], value_vars =['B'])


Python3
# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.DataFrame({"A":[12, 4, 5, 44, 1],
                   "B":[5, 2, 54, 3, 2], 
                   "C":[20, 16, 7, 3, 8], 
                   "D":[14, 3, 17, 2, 6]})
  
# Print the dataframe
df


Python3
# function to unpivot the dataframe
# We will also provide a customized name to the value and variable column
  
df.melt(id_vars =['A'], value_vars =['B', 'C'], 
        var_name ='Variable_column', value_name ='Value_column')


让我们使用dataframe.melt()函数将“A”列设置为标识符变量,将“B”列设置为值变量。

Python3

# function to unpivot the dataframe
df.melt(id_vars =['A'], value_vars =['B'])

输出 :
示例 #2:使用melt()函数将“A”列设置为标识符变量,将“B”和“C”列设置为值变量。还可以自定义值和变量列的名称。

Python3

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.DataFrame({"A":[12, 4, 5, 44, 1],
                   "B":[5, 2, 54, 3, 2], 
                   "C":[20, 16, 7, 3, 8], 
                   "D":[14, 3, 17, 2, 6]})
  
# Print the dataframe
df

让我们使用dataframe.melt()函数将列“A”设置为标识符变量,将列“B”和“C”设置为值变量。

Python3

# function to unpivot the dataframe
# We will also provide a customized name to the value and variable column
  
df.melt(id_vars =['A'], value_vars =['B', 'C'], 
        var_name ='Variable_column', value_name ='Value_column')

输出 :