我在我的数据框上运行以下代码函数:
del dfname["Unnamed: 0"]
dfname["date"] = pd.to_datetime(dfname["date"])
dfname.set_index(dfname["date"], drop=True, inplace=True)
但是列没有drop(我知道默认是drop=True
)
The output dataframe looks like this .我正在使用 Python 3.6
最佳答案
将 DataFrame 的列更改为列名,drop = True
也是默认的,因此可以将其删除:
dfname.set_index(dfname["date"], drop = True, inplace = True)
到:
dfname.set_index("date", inplace = True)
示例:
rng = pd.date_range('2017-04-03', periods=10)
dfname = pd.DataFrame({'date': rng, 'a': range(10)})
dfname.set_index("date", inplace = True)
print (dfname)
a
date
2017-04-03 0
2017-04-04 1
2017-04-05 2
2017-04-06 3
2017-04-07 4
2017-04-08 5
2017-04-09 6
2017-04-10 7
2017-04-11 8
2017-04-12 9
编辑:
如果输入是文件,使用read_csv
DatetimeIndex
的参数 index_col
和 parse_dates
:
df = pd.read_csv(file, index_col=['date'], parse_dates=['date'])
关于python - Pandas set_index 不会删除该列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48889914/