亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數據框列類型更改為 int32

將數據框列類型更改為 int32

繁花如伊 2023-02-15 15:53:49
我正在嘗試將數據框列從 Python 傳遞到 Cython:Python代碼evaluate_c(        AnimalLogicPy(data[COL_ANIMAL_ID].values,                      data[COL_ANIMAL_POWER].values,        )賽通代碼cpdef void evaluate_c(        int[:] animal_ids,        int[:] animal_power,        ):在 Python 端data[COL_ANIMAL_ID],data[COL_ANIMAL_POWER]類型為:int64但是我收到以下錯誤:ValueError: Buffer dtype mismatch, expected 'int' but got 'long'我想int在 Cython 中使用值。我已經閱讀了一些內容,我認為這是因為所討論的數據框列屬于int64我認為正在變得很長并且應該是int32.我嘗試在 Python 端使用以下方法更改類型:data.astype({COL_ANIMAL_ID: 'int32'}).dtypesdata.astype({COL_ANIMAL_POWER: 'int32'}).dtypes但我仍然得到 ValueError。如何將 Python 端的列類型從 int64 更改為 int32?
查看完整描述

1 回答

?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

您可以將其轉換為具有正確dtype.

有多種方法可以實現這一點,其中最直接的方法是通過以下.to_numpy()方法:

data[COL_ANIMAL_ID].to_numpy('int32')

為了給你一個最小的工作示例,讓我們假設我們有以下 Cython 函數(為簡單起見,使用 IPython 的 Cython magic 編譯):

%%cython -c-O3 -c-march=native -a

#cython: language_level=3, boundscheck=False, wraparound=False, initializedcheck=False, cdivision=True, infer_types=True



cpdef int summer(int [:] data, int n):

    cdef int result = 0

    for i in range(n):

        result += data[i]

    return result

然后下面的代碼工作:


import pandas as pd

import numpy as np



np.random.seed(0)

df = pd.DataFrame(np.random.randint(0, 100, (3, 4)))

print(df)

#     0   1   2   3

# 0  44  47  64  67

# 1  67   9  83  21

# 2  36  87  70  88



arr = np.array(df[0], dtype=np.int32)

print(summer(arr, arr.size))  # the array is fed to the Cython func

# 147


print(summer(df[0].values.astype(np.int32), df[0].size))  # directly from the Pandas's series

# 147


print(summer(df[0].to_numpy(dtype=np.int32), df[0].size))  # even more concisely

# 147


print(df[0].sum())  # checking that the result is correct

# 147


查看完整回答
反對 回復 2023-02-15
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號