Pandas set_index不会删除列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pandas set_index不会删除列相关的知识,希望对你有一定的参考价值。

我导入了几个csv文件并运行此函数:

def csv_bereinigen(dfname):
    del dfname["Unnamed: 0"]
    dfname["date"] = pd.to_datetime(dfname["date"])
    dfname.set_index(dfname["date"], drop = True, inplace = True)

但该列不会丢弃(我知道drop的默认值为True)

Output 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_csvindex_colparse_datesDatetimeIndex

df = pd.read_csv(file, index_col=['date'], parse_dates=['date'])

以上是关于Pandas set_index不会删除列的主要内容,如果未能解决你的问题,请参考以下文章