mat*_*ick 11 python numpy pandas
假设我有一个如下所示的重组:
import numpy as np
# example data from @unutbu's answer
recs = [('Bill', '31', 260.0), ('Fred', 15, '145.0')]
r = np.rec.fromrecords(recs, formats = 'S30,i2,f4', names = 'name, age, weight')
print(r)
# [('Bill', 31, 260.0) ('Fred', 15, 145.0)]
Run Code Online (Sandbox Code Playgroud)
假设我想将某些列转换为浮点数.我该怎么做呢?我应该换成一个ndarray,然后再回到recarray吗?
unu*_*tbu 16
以下是astype用于执行转换的示例:
import numpy as np
recs = [('Bill', '31', 260.0), ('Fred', 15, '145.0')]
r = np.rec.fromrecords(recs, formats = 'S30,i2,f4', names = 'name, age, weight')
print(r)
# [('Bill', 31, 260.0) ('Fred', 15, 145.0)]
Run Code Online (Sandbox Code Playgroud)
的age是D型细胞<i2:
print(r.dtype)
# [('name', '|S30'), ('age', '<i2'), ('weight', '<f4')]
Run Code Online (Sandbox Code Playgroud)
我们可以改为<f4使用astype:
r = r.astype([('name', '|S30'), ('age', '<f4'), ('weight', '<f4')])
print(r)
# [('Bill', 31.0, 260.0) ('Fred', 15.0, 145.0)]
Run Code Online (Sandbox Code Playgroud)
mat*_*ick 14
基本上有两个步骤.我的绊脚石是找到如何修改现有的dtype.我就这样做了:
# change dtype by making a whole new array
dt = data.dtype
dt = dt.descr # this is now a modifiable list, can't modify numpy.dtype
# change the type of the first col:
dt[0] = (dt[0][0], 'float64')
dt = numpy.dtype(dt)
# data = numpy.array(data, dtype=dt) # option 1
data = data.astype(dt)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14028 次 |
| 最近记录: |