2017-05-25 50 views
0

我有一個簡單的數據輸入表單,將輸入寫入csv文件。一切似乎都工作正常,除了有些額外的列被添加到文件中的某個地方,似乎是在用戶輸入階段。下面是代碼:以用戶輸入形式添加的未知列

import pandas as pd 

#adds all spreadsheets into one list 
Batteries= ["MAT0001.csv","MAT0002.csv", "MAT0003.csv", "MAT0004.csv", 
"MAT0005.csv", "MAT0006.csv", "MAT0007.csv", "MAT0008.csv"] 


#User selects battery to log 
choice = (int(input("Which battery? (1-8):"))) 
def choosebattery(c): 
    done = False 
    while not done: 
     if(c in range(1,9)): 
      return Batteries[c] 
      done = True 
     else: 
      print('Sorry, selection must be between 1-8') 
cfile = choosebattery(choice) 

cbat = pd.read_csv(cfile) 


#Collect Cycle input 
print ("Enter Current Cycle") 
response = None 
while response not in {"Y", "N", "y", "n"}: 
    response = input("Please enter Y or N: ") 
    cy = response 

#Charger input  
print ("Enter Current Charger") 
response = None 
while response not in {"SC-G", "QS", "Bosca", "off", "other"}: 
    response = input("Please enter one: 'SC-G', 'QS', 'Bosca', 'off', 'other'") 
    if response == "other": 
     explain = input("Please explain") 
     ch = response + ":" + explain 
    else: 
     ch = response 

#Location 
print ("Enter Current Location") 
response = None 
while response not in {"Rack 1", "Rack 2", "Rack 3", "Rack 4", "EV001", "EV002", "EV003", "EV004", "Floor", "other"}: 
    response = input("Please enter one: 'Rack 1 - 4', 'EV001 - 004', 'Floor' or 'other'") 
    if response == "other": 
     explain = input("Please explain") 
     lo = response + ":" + explain 
    else: 
     lo = response  

#Voltage   
done = False 
while not done: 
    choice = (float(input("Enter Current Voltage:"))) 
    modchoice = choice * 10 
    if(modchoice in range(500,700)): 
     vo = choice 
     done = True 
    else: 
     print('Sorry, selection must be between 50 and 70') 


#add inputs to current battery dataframe 
log = pd.DataFrame([[cy,ch,lo,vo]],columns=["Cycle", "Charger", "Location", "Voltage"]) 
clog = pd.concat([cbat,log], axis=0) 




clog.to_csv(cfile, index = False) 
pd.read_csv(cfile) 

我收到:

Out[18]: 
    Charger Cycle Location Unnamed: 0 Voltage 
0  off  n  Floor   NaN  50.0 

哪裏是 「未命名」 一欄是從哪裏來的?

回答

0

有一個來自您的csv的'未命名'列。原因很可能是輸入csv文件中的行以逗號(即分隔符)結尾,因此大熊貓會將其解釋爲額外的(無名稱)列。如果是這樣,請檢查您的線路是否以分隔符結束。例如,如果你的文件是用逗號分隔:

Column1,Column2,Column3, 
val_11, val12, val12, 
... 

分爲:

Column1,Column2,Column3 
val_11, val12, val12 
... 

或者,嘗試顯式指定索引列在this answer。我相信一些混淆源於熊貓concatreordering your columns

+0

第一個想法看起來很有希望,儘管我想不出如何解決這個問題。由於我已經通過了index = False,它必須是索引以外的東西。我很茫然,我似乎無法找到一個簡單的解決方法,我應該使用不同的方法或數據結構? – Josmolio

+0

@Josmolio如果是這種情況,只需刪除每行中的尾隨分隔符。我用一個例子更新了這個問題 – vmg