我有一个来自网站的 Dataframe,并将前几行用作 Date 。它向我显示了带有 Yr_Mn_Dy 的 Df,但它看起来不错,所以我想将其更改为 Dates。
df = pd.read_csv('https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data', sep='\s+', parse_dates = [[0,1,2]] )
df.head()
Yr_Mo_Dy RPT ... BEL MAL
0 2061-01-01 15.04 ... 18.50 15.04
1 2061-01-02 14.71 ... 17.54 13.83
2 2061-01-03 18.50 ... 12.75 12.71
3 2061-01-04 10.58 ... 5.46 10.88
4 2061-01-05 13.33 ... 12.92 11.83
我一一使用了2种不同的方法
1. df.rename(columns= {'Yr_Mo_Dy': 'Dates'}) # it does not work. it is not changing the columns names to Dates
and
2. df.columns.values[0]='Dates' # it changes the values when used with df.head() but throws Key error for Dates
<强> 1。为什么第一种方法不更改值并重命名列? 强>
<强>
2。即使在使用第二种方法更改值后,为什么会抛出
Dates Key 错误?
强>
请您参考如下方法:
第一种方法可以更改列名,在我的电脑上效果很好,
请注意,它不会更改原始数据框,而是返回一个新的数据框,以使更改永久化,
df.rename(columns= {'Yr_Mo_Dy': 'Dates'},inplace=True)
第二种方法也有效,它不会抛出 Dates Key 错误。
