Pandas set_index不会删除列

问题描述 投票:3回答:1

我导入了几个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)

python pandas csv import
1个回答
5
投票

将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'])
© www.soinside.com 2019 - 2024. All rights reserved.