python - 对特定索引应用 .astype() 不起作用
问题描述
我想在 dnarray 中将第一列更改为 int
print(gcp)
[[ 1. 6.218 2.974 0. ] [ 2. 32.881 8.66 0. ] [ 3.
38.94 35.843 0. ] [ 4. 8.52 35.679 0. ] [ 5. 52.902 49.538 0. ]]
print(gcp.dtype)
浮动64
gcp[:,0] = (gcp[:,0]).astype(int)
print(((gcp[:,0]).astype(int)).dtype)
整数32
print(gcp.dtype)
浮动64
我尝试使用 deepcopy,但没有成功。任何帮助都会很好,我没有发现任何类似的问题。
解决方案
只拥有index of the row(+1)
数组的 as 元素对我来说似乎是多余的,也许您根本不需要第一行。否则对我来说最好的选择是使用两个数组:
gcp0 = gcp[:, 0].astype(int)
gcp = gcp[:, 1:]
另一种可能性是为单独的列named fields
分别定义单独dtypes
的列,这可能使您更接近pandas
,这是您拥有的另一个选项。
gcp = np.array([(1., 6.218, 2.974, 0.),
(2., 32.881, 8.66, 0.),
(3., 38.94, 35.843, 0.),
(4., 8.52, 35.679, 0.),
(5., 52.902, 49.538, 0.)],
dtype={'names': ['index', 'a0', 'a1', 'a2'],
'formats': [int, float, float, float]})
print(gcp['index'])
# [1 2 3 4 5]
推荐阅读
- reactjs - 在应用程序中反应 setstatus 问题
- r - httr POST 请求错误:上游连接错误或在标头之前断开/重置。重置原因:连接终止
- asp.net-core - 剃须刀页面如何显示图片?
- javascript - 您如何运行服务器端脚本而不将其发送到浏览器?
- laravel - 如何在 laravel jetstream 中重定向?
- jenkins - 在全球范围内跳过 Jenkins 管道中的一个阶段
- c++ - 使用 pqxx 从 postgres 读取/写入大对象
- sockets - boost::asio::async_write 函数有什么用
- angular - 无法用 [hidden] 隐藏跨度
- vue.js - Vue 3 Web 组件不构建而是抛出错误