问题出在重命名 pandas 中的列

Problem is in renaming the columns in pandas

提问人:Azize Lbaibi 提问时间:11/16/2023 最后编辑:RobertAzize Lbaibi 更新时间:11/17/2023 访问量:93

问:

需要给出列名才能在函数的其余部分调用它们,但我不知道为什么会有这个问题。即使看起来不错,有人可以帮我解决熊猫的这个问题吗?

这是代码:

import pandas as pd

# Chemin du fichier CSV
file_path_asset = 'C://Users//AZLBAIBI//Desktop//Ex2 TP//Asset.csv'

# Lire le fichier CSV dans un DataFrame
data =pd.read_csv(file_path_asset, skiprows=0 ,delimiter=',')

# Renommer les colonnes 
data.columns = ["asset_id", "asset_reference", "asset_type", "product_warranty_start_date", "product_warranty_end_date"]


print(data) #### The problem is in renaming the columns. I don't know how to fix this issue 

在此处输入图像描述 在此处输入图像描述

Python Pandas 数据帧

评论

0赞 Panda Kim 11/16/2023
你能打开你的CSV文件,并提供文件的前三行作为文本吗?
0赞 planetmaker 11/17/2023
请引用文本输出而不是图像

答:

1赞 Michal Shilo 11/16/2023 #1

如果没有 csv 的样本,很难回答, 但是,当您从 CSV 加载时,您应该弄清楚列名是什么。然后,我更喜欢创建一个字典,在要重命名的旧列名和新列名之间进行转换。 然后使用 pd。DataFrame.rename:

假设加载 CSV 后的列名是

['col1', 'col2', 'col3','col4', 'col5']

新名称是

["asset_id", "asset_reference", "asset_type", "product_warranty_start_date", "product_warranty_end_date"]

这是重命名列的方法:

column_mapper_dict = {
'col1': 'asset_id',
'col2': 'asset_reference',
'col3': 'asset_type',
'col4': 'product_warranty_start_date',
'col5': 'product_warranty_end_date'
}
data = data.rename(columns=column_mapper_dict)

评论

1赞 user19077881 11/16/2023
熊猫接受该语句或任何语句,只要列数与 DF 匹配;这些列将按“列出”的顺序重命名。目前尚不清楚为什么 OP 有问题。df.columns = ['col1', 'col2']
0赞 Michal Shilo 11/17/2023
谢谢,我不知道。我编辑了我的答案