如何用Pandas将DataFrame多列转换为单列LOCATOR格式?
Pandas宽格式DataFrame转长格式(ID、Name、LOCATOR)
我有一个宽格式的Pandas DataFrame,包含ID、Name、Mail、Phone1、Phone2、Mail1、Mail2、contact phone、contact mail列,数据示例如下:
| ID | Name | Phone1 | Phone2 | Mail1 | Mail2 | contact phone | contact mail | |
|---|---|---|---|---|---|---|---|---|
| 70 | DASS ARGENTINA SRL | info@iricresanluis.com.ar | 2664941642 | 2664941644 | info@iricresanluis.com.ar | info_tec@iricresanluis.com.ar | 115456789 | contact_mail@gmail.com |
| 71 | PEPSI | mail_general@pepsi.com | 0456535365 | 7766554399 | mail1@pepsi.com | mail2@pepsi.com | 8864545332 | last_mail@pepsi.com |
希望将其转换为仅含ID、Name、LOCATOR列的长格式DataFrame,示例如下:
| ID | Name | LOCATOR |
|---|---|---|
| 70 | DASS ARGENTINA SRL | info@iricresanluis.com.ar |
| 70 | DASS ARGENTINA SRL | 2664941642 |
| 70 | DASS ARGENTINA SRL | 2664941644 |
| 70 | DASS ARGENTINA SRL | info@iricresanluis.com.ar |
| 70 | DASS ARGENTINA SRL | info_tec@iricresanluis.com.ar |
| 70 | DASS ARGENTINA SRL | 115456789 |
| 70 | DASS ARGENTINA SRL | contact_mail@gmail.com |
| 71 | PEPSI | mail_general@pepsi.com |
| 71 | PEPSI | 0456535365 |
| 71 | PEPSI | 7766554399 |
| 71 | PEPSI | mail1@pepsi.com |
| 71 | PEPSI | mail2@pepsi.com |
| 71 | PEPSI | 8864545332 |
| 71 | PEPSI | last_mail@pepsi.com |
我尝试使用transpose函数,但未能得到预期的输出格式,请问是否可以实现该转换?
解决方案
当然可以实现,transpose函数是用来转置整个DataFrame的行列,并不适合这种宽表转长表的场景,正确的做法是使用Pandas的melt函数,它专门用于将宽格式数据重塑为长格式。
代码实现
import pandas as pd # 构建示例数据 data = { 'ID': [70, 71], 'Name': ['DASS ARGENTINA SRL', 'PEPSI'], 'Mail': ['info@iricresanluis.com.ar', 'mail_general@pepsi.com'], 'Phone1': ['2664941642', '0456535365'], 'Phone2': ['2664941644', '7766554399'], 'Mail1': ['info@iricresanluis.com.ar', 'mail1@pepsi.com'], 'Mail2': ['info_tec@iricresanluis.com.ar', 'mail2@pepsi.com'], 'contact phone': ['115456789', '8864545332'], 'contact mail': ['contact_mail@gmail.com', 'last_mail@pepsi.com'] } df = pd.DataFrame(data) # 使用melt转换格式 long_df = df.melt( id_vars=['ID', 'Name'], # 保持不变的列 value_vars=['Mail', 'Phone1', 'Phone2', 'Mail1', 'Mail2', 'contact phone', 'contact mail'], # 需要转换的列 value_name='LOCATOR' # 转换后值的列名 ).drop(columns=['variable']) # 删除自动生成的原列名列 # 重置索引(可选) long_df = long_df.reset_index(drop=True) print(long_df)
代码说明
id_vars:指定转换过程中保持不变的列,即ID和Name,每一行的这两个值会和所有待转换列的值一一对应。value_vars:列出需要被“融化”合并到LOCATOR列的所有字段,这些字段的所有值都会被整合到新的LOCATOR列中。value_name:定义新生成的数值列的名称,这里就是我们需要的LOCATOR。- 最后删除
melt自动生成的variable列(存储原列名),得到完全符合需求的长格式DataFrame。
运行代码后即可得到目标格式的结果。
内容的提问来源于stack exchange,提问作者Maximiliano Vazquez
相关产品推荐
相关产品推荐

