我写的代码对于csv文件正常工作,但是如果我将文件类型从csv更改为excel,则会给我一个错误。
我有data = pd.read_excel(filename)
,如果我写data = pd.read_csv(filename)
的话,以上几行对excel不起作用,它工作正常。而且我希望我的Excel中的输入数据不是csv。
import tkinter as tk
import pandas as pd
from tkinter.filedialog import askopenfilename
import xlrd
def latlong_func(filename):
# filename instead of r'C:/Users/patesari/Desktop/python work/Gap1.csv'
data = pd.read_excel(filename)
#df = pd.DataFrame(data, columns=['SUPPLIER_ID','ACTION'])
data["latlong"] = 'FALSE'
data.loc[
(data["LONGITUDE"] >= 70.0000) & (data["LONGITUDE"] <= 98.0000) &
(data["LONGITUDE"] != 'nan') & (data["LATITUDE"] != 'nan')&
(data["LATITUDE"] >= 6.0000) & (data["LATITUDE"] <= 36.000),
["latlong"]] = ''
data.to_csv("practice1.csv")
writer = data[data["latlong"]=='']
writer.to_csv('newfile1.csv')
writer.to_csv('latlong1.csv')
print("Kindly ignore the message..your output is genrated sucessfully....")
def get_filename():
filename = askopenfilename(filetypes =[('Python Files', '*.xlsx')])
if filename:
lbl['text'] = filename # display filename in Label
latlong_func(filename)
else:
lbl['text'] = 'not selected'
# --- main ---
root = tk.Tk()
root.geometry('200x100')
lbl = tk.Label(root, text='Select filename')
lbl.pack(side='top', pady=10)
btn = tk.Button(root, text='Open', command=get_filename)
btn.pack(side='top', pady=10)
root.mainloop()
请有人帮助我知道我在哪里做错了。 我收到此错误:
Traceback (most recent call last):
File "C:\Users\patesari\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\indexes\base.py", line 2890, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'LONGITUDE'
答案 0 :(得分:0)
您好,请检查您的Excel文件扩展名
假设
如果filename=file.csv
,那么data=pd.read_csv(filename)
会起作用
OR
如果filename=file.xlsx
,那么data=pd.read_excel(filename)
可以工作
如果您想在excel中输入数据而不是csv,那么
使用下面的代码将.csv转换为.xlsx,然后选择该转换后的文件
并使用data=pd.read_csv(filename)
来读取您的Excel文件
export_excel = df.to_excel ('file_path_to_save', index = None, header=True)#Don't forget to add '.xlsx' at the end of the path
希望这对您有用
如果我的回答为您提供了解决方案,请投票谢谢
答案 1 :(得分:0)
KeyError:'LONGITUDE'