提问人:Azize Lbaibi 提问时间:11/16/2023 最后编辑:RobertAzize Lbaibi 更新时间:11/17/2023 访问量:93
问题出在重命名 pandas 中的列
Problem is in renaming the columns in pandas
问:
需要给出列名才能在函数的其余部分调用它们,但我不知道为什么会有这个问题。即使看起来不错,有人可以帮我解决熊猫的这个问题吗?
这是代码:
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
答:
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
谢谢,我不知道。我编辑了我的答案
评论