1

最初の行がヘッダーである csv ファイルを解析しています。日付に従って金額列を合計したいのですが、エラー メッセージが表示されます。デバッグするために、エラーメッセージに従って列が数字であるかどうかと文字列であるかどうかを確認しています-そしてそれは両方です。この理由は何でしょうか?

def parseDataFromFile(self,f):
    fh = open(f,'r')
    s = 0
    for line in fh:
        #parsing the line according to comma and stripping the '\n' char
        year,month,day,amount = line.strip('\n').split(',')

        #checking the header row, could check if was first row as well - would be faster
        if (amount == "Amount"): continue

        #just for the debug checks
        #here is the question

        if isinstance(amount,str):
            print "amount is a string"
            #continue
        if amount.isdigit:
            print "amount is a digit"

        #sum on the amount column
        s = s + amount

出力: 金額は文字列です 金額は数字です 金額は文字列です 金額は数字です

エラー:

s = s + amount 
TypeError: unsupported operand type(s) for +: 'int' and 'str'
4

4 に答える 4

5

あなたの問題は、それsが整数であることです。それを に初期化し0ます。次に、それに文字列を追加しようとします。amountは常に文字列です。数値のようなデータを実際の数値に変換するために何もしません。常に文字列になります。

金額が数値であると予想される場合は、次を使用します。

s += float(amount)

PS: csvCSV ファイルを読み取るには、stdlib のモジュールを使用する必要があります。

于 2012-07-17T14:21:08.653 に答える
1
if amount.isdigit:
    print "amount is a digit"

メソッドを呼び出していないため、常に「金額は数字です」と出力されます(そうである必要がありますif amount.isdigit():)。

CSV ファイルから行を分割して取得したフィールドはすべて文字列であることを確認できます。最初に int に変換する必要があります。

s = s + int(amount)
于 2012-07-17T14:21:42.130 に答える
0

次のようなものですか?:(列ヘッダーが「Year」、「Month」、「Day」、「Amount」であると想定)

from collections import defaultdict
import csv

sum_by_ym = defaultdict(float)
with open('input_file.csv') as f:
    for row in csv.DictReader(f):
        sum_by_ym[(row['Year'], row['Month'])] += int(float['Amount'])

print sum_by_ym
于 2012-07-17T14:34:26.953 に答える
0

s は int で、amount は数値の文字列表現なので、次のように変更s = s + amountします。s += int(amount)

于 2012-07-17T14:21:15.053 に答える