你所得到的錯誤是因爲對方的回答表明,你不能使用data['Name'] = 'peter'
作爲函數參數,你居然打算用 - np.where(data['Name'] == 'peter')
。
但是,鑑於您使用的是pandas
,而且我猜測data
是一個熊貓DataFrame
。在這種情況下,您真正想要的可以使用DataFrame.groupby
來實現。示例 -
data[data['Name']=='peter'].groupby('Item').count()
演示 -
In [7]: data[data['Name']=='peter'].groupby('Item').count()
Out[7]:
Name
Item
apple 2
banana 1
如果你想這樣的循環打印,你可以使用 -
df = data[data['Name']=='peter'].groupby('Item').count()
for fruit,count in df['Name'].iteritems():
print('{0}\t{1}'.format(fruit,count))
演示 -
In [24]: df = data[data['Name']=='peter'].groupby('Item').count()
In [25]: for fruit,count in df['Name'].iteritems():
....: print('{0}\t{1}'.format(fruit,count))
....:
apple 2
banana 1
對於更新的問題是,OP漸漸,他在那裏發現了以下錯誤 -
TypeError: invalid type comparison
在這種情況下,因爲在OP真實的數據出現問題,列有數值( float/int),但是OP將這些值與字符串進行比較,從而得出錯誤。示例 -
In [30]: df
Out[30]:
0 1
0 1 2
In [31]: df[0]=='asd'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-31-e7bacd79d320> in <module>()
----> 1 df[0]=='asd'
C:\Anaconda3\lib\site-packages\pandas\core\ops.py in wrapper(self, other, axis)
612
613 # scalars
--> 614 res = na_op(values, other)
615 if np.isscalar(res):
616 raise TypeError('Could not compare %s type with Series'
C:\Anaconda3\lib\site-packages\pandas\core\ops.py in na_op(x, y)
566 result = getattr(x, name)(y)
567 if result is NotImplemented:
--> 568 raise TypeError("invalid type comparison")
569 except (AttributeError):
570 result = op(x, y)
TypeError: invalid type comparison
如果您的列是數字,則應該與數字值進行比較,而不是字符串。
錯誤:關鍵字不能表達 – aaaabbbb
什麼是'data'?熊貓DataFrame? Numpy記錄陣列?哪一行你得到的錯誤 –
我用熊貓閱讀我的數據文件 – aaaabbbb