尝试在Pandas中运行dataframe.at时遇到KeyError

时间:2020-05-09 16:41:13

标签: python pandas dataframe

我试图编写一个输入分钟数的程序。在输出中,应在CSV文件中添加程序运行的次数(频率)和累积的分钟数(累积)。 CSV文件应按月进行。这是我的代码。

import pandas as pd, numpy as np
import time, winsound

x = dt.datetime.now()
z = x.strftime("%b %Y") #month-year
m = x.strftime("%b %d") #month-day
frequency = 555  
duration = 3000

def myTimer():
    minutes = int(input("How many minutes? "))
    seconds = minutes*60
    for i in range(seconds):
        print(str(seconds - i) + " seconds remain")
        time.sleep(1)

    if os.path.isfile(z+".csv"):
        df1 = pd.read_csv(z+".csv", index_col=0)
        df1.index = df1.index.astype('str')

        #For incrementing on existing same date 
        m_count = df1.index.str.contains(m).sum()            
        if m_count > 0:
            dayOfMonth = str(int(x.strftime("%d")))        
            month = x.strftime("%b")
            new_index = month + " " + dayOfMonth

            w = df1.at[new_index, 'Cumulative']
            p = np.int16(w).item()
            p += minutes
            df1.at[new_index, 'Cumulative'] = np.int64(p)

            y = df1.at[new_index, 'Frequency']
            u = np.int16(y).item()
            u += 1
            df1.at[new_index, 'Frequency'] = np.int64(u)

            df1.to_csv(z+'.csv')

        #Creating a new date 
        #Give it its first entry only 
        else:
            df3 = pd.read_csv(z+".csv", index_col=0)

            #To make Frequency and Cumulative == 0
            dayOfMonth3 = str(int(x.strftime("%d")))        
            month3 = x.strftime("%b")
            new_index3 = month3 + " " + dayOfMonth3
            b1 = 0
            b1 += 1
            df3.at[new_index3, 'Frequency'] = np.int64(b1)
            a1 = 0
            a1 += minutes
            df3.at[new_index3, 'Cumulative'] = np.int64(a1)

            df3.to_csv(z+'.csv')

    else:
        df2 = pd.DataFrame([m], columns=['Date'])

        #Settidf1y and Cumulative to 0
        df2['Frequency'] = 0
        df2['Cumulative'] = 0  

        #Adding 1 and 25 to above new columns
        b = 0
        b += 1
        df2.at[0, 'Frequency'] = np.int64(b)
        a = 0
        a += minutes
        df2.at[0, 'Cumulative'] = np.int64(a)

        # print(df2)
        df2.to_csv(z+'.csv', index=False)

myTimer()
winsound.Beep(frequency, duration)

我得到的错误是

  File "C:\Users\user\Anaconda3\envs\scrapy\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
KeyError: 'May 9'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Timer.py", line 78, in <module>
    myTimer()
  File "Timer.py", line 29, in myTimer
    w = df1.at[new_index, 'Cumulative']
File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'May 9'

我的预期输出是这样的enter image description here这是上个月的。对于这个月,它将显示5月而不是4月

编辑: df1.head()打印出以下内容 enter image description here

1 个答案:

答案 0 :(得分:0)

更改此行代码:

dayOfMonth = str(int(x.strftime("%d")))

收件人:

dayOfMonth = (x.strftime("%d"))

应该可以解决此问题。 在一个月的1-9天中,str(int(x.strftime(“%d”)))返回'9'而不是'09',这是导致问题的原因。