簡體   English   中英

當我運行以下代碼時,出現以下錯誤:ValueError:int()以10為底的無效文字:“((1,0,'Friday')”

[英]When I run the following code,I get this error:ValueError: invalid literal for int() with base 10: “(1, 0, 'Friday')”

當我運行以下代碼時,我得到了

ValueError: invalid literal for int()  with base 10: "(1, 0, 'Friday')" 

指向線:

monthwise = list(map(int, read_from_csv(infile_csv, month=True)[0])) .

我已經包含了示例.csv文件

輸出:我需要比較訂戶和客戶每月讀者人數的圖

import calendar  
import datetime 
infile_csv = 'C:/pythonscripts/NYC-2016-Summary.csv'   
def read_from_csv(input_csvfile, duration=False, month=False, hour=False, day_of_week=False):    

# assign columns name
if duration==True:
    col_name='duration'
elif month==True:
    col_name='month'
elif hour==True:
    col_name='hour'
elif day_of_week==True:
    col_name='day_of_week'

# init lists for output
n_ridership4column = []
n_ridership_sub = []
n_ridership_cust = []

with open(infile_csv, 'r') as f_in:
    filereader = csv.DictReader(f_in)
    for row in filereader:
        n_ridership4column.append(row[col_name])
        if row['user_type'] == 'Subscriber':
            n_ridership_sub.append(row[col_name])
        else:
            n_ridership_cust.append(row[col_name])

return n_ridership4column, n_ridership_sub, n_ridership_cust

# using the function above to get monthly ridership

monthwise = list(map(int, read_from_csv(infile_csv, month=True)[0]))   
monthwise_sub = list(map(int, read_from_csv(infile_csv, month=True)[1])) 
monthwise_cust = list(map(int, read_from_csv(infile_csv, month=True)[2]))  

以下代碼用於繪圖。 對於問題而言,這不是必需的,但對於輸出的清晰性而言,則不是必需的。

fig, ax = plt.subplots()
bins = [i for i in range(1,14)]                 
#upper bound is 14 to accomodate bin for december

#### Plotting monthly total along with customers and subscribers stacked

ax.hist(monthwise, bins=bins, edgecolor='k', align='left', label='Total Ridership', stacked= True)   
ax.hist(monthwise_sub, bins=bins, edgecolor='k', align='left', label='Subscribers', stacked=True)
ax.hist(monthwise_cust, bins=bins, edgecolor='k', align='left', label='Customer', stacked=True)

ax.set_xticks(bins[:-1])
ax.set_xticklabels(list(calendar.month_abbr[i] for i in bins[:-1]))


plt.title('Monthly Ridership in NYC', fontsize=16)
plt.xlabel('Monthly', fontsize=14)  
plt.ylabel('Rides', fontsize=14)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)

plt.legend()
plt.show()

這是上面代碼的示例.csv文件

duration    month   hour    day_of_week user_type
13.98333333 (1, 0, 'Friday')        (1, 0, 'Friday')    Customer
11.43333333 (1, 0, 'Friday')        (1, 0, 'Friday')    Subscriber
5.25    (1, 0, 'Friday')        (1, 0, 'Friday')    Subscriber
12.31666667 (1, 0, 'Friday')        (1, 0, 'Friday')    Subscriber
20.88333333 (1, 0, 'Friday')        (1, 0, 'Friday')    Customer
8.75    (1, 0, 'Friday')        (1, 0, 'Friday')    Subscriber
10.98333333 (1, 0, 'Friday')        (1, 0, 'Friday')    Subscriber
7.733333333 (1, 1, 'Friday')        (1, 1, 'Friday')    Subscriber
3.433333333 (1, 1, 'Friday')        (1, 1, 'Friday')    Subscriber
7.083333333 (1, 1, 'Friday')        (1, 1, 'Friday')    Customer
13.3    (1, 2, 'Friday')        (1, 2, 'Friday')    Subscriber
9.733333333 (1, 2, 'Friday')        (1, 2, 'Friday')    Subscriber
8.416666667 (1, 2, 'Friday')        (1, 2, 'Friday')    Subscriber

錯誤消息表示您正在嘗試將非數字值解析為整數。 當您要求Python執行其無法執行的操作(將數字除以零,引用未聲明的變量等)時,它將引發錯誤。 通常,錯誤消息很清楚,盡管當您僅學習Python時,有時您需要使用google。

就應負責任的程度而言,無論哪個程序編寫此錯誤的CSV都是錯誤的,應予以修復或替換。 為了使CSV有用,需要將其標准化為每個字段一個基准,盡管您有時會發現違反此原則。 至少以Python特定格式編寫復合字段是錯誤的,在這種情況下很可能是一個錯誤。

此外,樣本數據中的一列比樣本標題所建議的少一列。 另一方面,第2列和第3列始終看起來是相同的,並且模糊地似乎由適合表頭中第2列,第3列和第4列的預期值的值組成。

您的代碼很奇怪,因為它似乎在每次要提取列時都讀取文件。 如果您的輸入文件太大而無法一次全部放入內存,那么這可能會有些含糊。 但是如果您的問題或代碼中的注釋中沒有任何此類問題,我建議一次將所有列讀入內存。 這也應該使您的程序至少快一個數量級。

DictReader已經負責將其輸入收集到OrderedDict因此循環中的append只是復制了該Python庫已經為您執行的工作。

如果您堅持使用此損壞的CSV,則可能會滿足您的需求。

def parse_broken_csv(filename):
    rows = []
    with open(filename, 'r') as fh:
        reader = csv.reader(fh, delimiter='\t')
        headers = reader.__next__()
        for duration, tpl, _, cust in reader:
            month, hour, dow = tpl.strip('()').split(', ')
            rows.append({
                'duration': float(duration),
                'month': int(month),
                'hour': int(hour),
                'day_of_week': dow.strip("'"),
                'cust': cust})
    return rows

rows = parse_broken_csv(r'NYC-2016-Summary.csv')

monthwise = [row['month'] for row in rows]
monthwise_sub = [row['month'] for row in rows if row['cust'] == 'Subscriber']
monthwise_cust = [row['month'] for row in rows if row['cust'] == 'Customer']

對於您發布的示例CSV, rows值為

[
 {'duration': 13.98333333, 'month': 1, 'day_of_week': 'Friday', 'cust': 'Customer', 'hour': 0},
 {'duration': 11.43333333, 'month': 1, 'day_of_week': 'Friday', 'cust': 'Subscriber', 'hour': 0},
 {'duration': 5.25, 'month': 1, 'day_of_week': 'Friday', 'cust': 'Subscriber', 'hour': 0},
 {'duration': 12.31666667, 'month': 1, 'day_of_week': 'Friday', 'cust': 'Subscriber', 'hour': 0},
 {'duration': 20.88333333, 'month': 1, 'day_of_week': 'Friday', 'cust': 'Customer', 'hour': 0},
 {'duration': 8.75, 'month': 1, 'day_of_week': 'Friday', 'cust': 'Subscriber', 'hour': 0},
 {'duration': 10.98333333, 'month': 1, 'day_of_week': 'Friday', 'cust': 'Subscriber', 'hour': 0}
]

並且monthwise的值是

[1, 1, 1, 1, 1, 1, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM