Python - 在 Pandas DataFrame 中明确命名列
要明确命名列,请使用 read_csv() 方法的 names 参数。假设以下内容是我们在 Microsoft Excel 中打开的不带头的 CSV 文件 -
让我们从 CSV 文件中加载数据,并使用 names 参数添加标题列 -
pd.read_csv("C:\Users\amit_\Desktop\TeamData.csv",names=['Team', 'Rank_Points', 'Year'])
示例
以下是完整代码 -
import pandas as pd # Load data from a CSV file into a Pandas DataFrame dataFrame = pd.read_csv("C:\Users\amit_\Desktop\TeamData.csv") print("Reading the CSV file without headers...\n", dataFrame) # adding headers dataFrame = pd.read_csv("C:\Users\amit_\Desktop\TeamData.csv",names=['Team', 'Rank_Points', 'Year']) # reading updated CSV print("\nReading the CSV file after updating headers...\n", dataFrame)
输出
这将产生以下输出 -
Reading the CSV file without headers... Australia 2500 2021 0 Bangladesh 1000 2021 1 England 2000 2021 2 India 3000 2021 3 Srilanka 1500 2021 Reading the CSV file after updating headers... Team Rank_Points Year 0 Australia 2500 2021 1 Bangladesh 1000 2021 2 England 2000 2021 3 India 3000 2021 4 Srilanka 1500 2021
广告