Pandas KeyError: value not in index

后端 未结 4 948
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 14:06

I have the following code,

df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=[\'Hour\'], columns=\'DOW\', values=\'Changes\', aggfunc=np.mean).round(0         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 14:52

    Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.

    p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])
    

    So, your entire code example should look like this:

    df = pd.read_csv(CsvFileName)
    
    p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
    p.fillna(0, inplace=True)
    
    columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
    p = p.reindex(columns=columns)
    p[columns] = p[columns].astype(int)
    

提交回复
热议问题