2016-11-21 95 views
0

我想了解如何在Python中使用Pandas。我正在對我的熊貓數據框做數學問題。 現在我的數據框看起來是這樣的:Python Panda錯誤類型錯誤:不支持的操作數類型爲:'str'和'int'

打印(標記)

   0  1  2  3  4   5    6 
0  447366345 -2.04 -2.69 176.98 418.84 34.3167521 -118.4068498 
1  447406197 -2.34 -2.18 176.88 418.77 34.3167522 -118.4068499 
2  447446155 -2.63 -1.56 176.74 418.77 34.3167522 -118.4068499 
3  447486653 -2.89 -0.95 176.58 418.84 34.3167522 -118.4068499 
4  447526241 -3.12 -0.42 176.43 418.84 34.3167522 -118.4068499 
5  447566373 -3.34 -0.07 176.32 418.84 34.3167522 -118.4068497 
6  447606036 -3.56 0.05 176.26 418.66 34.3167523 -118.4068497 
7  447645783 -3.77 -0.03 176.28 418.66 34.3167523 -118.4068497 
8  447686269 -3.95 -0.31 176.43 418.95 34.3167523 -118.4068497 

def data_reader(filename, rowname): 
    with open(filename, newline='') as fp: 
     yield from (row[1:] for row in csv.reader(fp, skipinitialspace=True) 
      if row[0] == rowname) 

mike = pd.DataFrame.from_records(data_reader('data.csv', 'mike')) 

現在,讓我們說,我想借此行0和1000

mark_time = mark[0]/1000 

這會產生錯誤把它

TypeError: unsupported operand type(s) for /: 'str' and 'int' 

我猜測,因爲目前我的數據幀不被視爲一個IN T,所以我繼續這樣做:

mark_time = float (mark[0]/1000) 

但是,這也給了我同樣的錯誤。有人可以向我解釋爲什麼?

我的第二個問題是關於繪圖。我已經很好地學習了matplotlib,並且我想在我的Panda數據框中使用它。目前我的做法是這樣的:

fig1 = plt.figure(figsize= (10,10)) 
ax = fig1.add_subplot(311) 
ax.plot(mike_time, mike[0], label='mike speed', color = 'red') 
plt.legend(loc='best',prop={'size':10}) 

我可以用我的數據幀替換mike_time和mike [0]嗎?

+5

類型'mark [0] = mark [0] .astype(int)' – EdChum

+5

'float(mark [0])/ 1000'而不是'float(mark [0]/1000)' – MMF

+0

@MMFI得到這個錯誤TypeError:無法將系列轉換爲

回答

1

您需要使用pandas.read_csv而不是python的csv。

在那裏,你可以使用D型參數爲它提供正確的數據類型爲它的使用方法:

從大熊貓documentation

dtype : Type name or dict of column -> type, default None Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32} (unsupported with engine='python'). Use str or object to preserve and not interpret dtype.

如果必須解析CSV外面大熊貓與進口「from_records」你可以使用coerce_float = True。 Reference

coerce_float : boolean, default False Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets

+0

我試過這個,但是我一直得到一個錯誤:TypeError:'dtype'是這個函數的一個無效的關鍵字參數。我這樣做的方式:csv.reader(fp,skipinitialspace = True,dtype = float) –

+1

這個答案是錯誤的,'pd.read_csv'會嘗試通過嗅探它們來推斷dtypes,OP使用'csv '這是完全不同的模塊 – EdChum

+0

這是真的@EdChum我更新了答案 – PabTorre

0

您需要使用pandas read_csv,它會自動爲每列分配最適當的類型。如果你有任何混合類型的列,它會警告你。然後您可以再次運行它,以明確設置類型。

+0

我試過這個,但我不斷收到錯誤:TypeError:'dtype'是這個函數的一個無效的關鍵字參數。我這樣做的方式:csv.reader(fp,skipinitialspace = True,dtype = float –

+1

您正在使用csv.reader,它是一個python函數,您需要使用pandas.read_csv – simon

+1

而且您不需要函數,只需df = pd.read_csv(「data.csv」) – simon

相關問題