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
添加回答
举报