GVKun编程网logo

numpy.loadtxt 转换器参数,使用 b'strings'(numpy str转float)

4

最近很多小伙伴都在问numpy.loadtxt转换器参数,使用b'strings'和numpystr转float这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展AnacondaNu

最近很多小伙伴都在问numpy.loadtxt 转换器参数,使用 b'strings'numpy str转float这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、android – setText(getString(R.strings.whatever)或setText(R.strings.whatever)?、cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”、ES6 Features 系列:Template Strings & Tagged Template Strings等相关知识,下面开始了哦!

本文目录一览:

numpy.loadtxt 转换器参数,使用 b'strings'(numpy str转float)

numpy.loadtxt 转换器参数,使用 b'strings'(numpy str转float)

如何解决numpy.loadtxt 转换器参数,使用 b''strings''?

这是第一次遇到使用 numpy.loadtxt 的代码。我阅读了官方文档,其中指出

转换器:字典,可选

一个将列号映射到一个函数的字典,该函数将解析 列字符串转换为所需的值。例如,如果第 0 列是日期 字符串:converters = {0: datestr2num}。转换器也可用于 为缺失数据提供默认值(但另请参见 genfromtxt): converters = {3: lambda s: float(s.strip() or 0)}。默认值:无。

我的理解是它将字符串转换为数值。但我不清楚它究竟是如何工作的。代码是:

labels = [b''NO'',b''DH'',b''SL'']
data = np.loadtxt(''column_3C.dat'',converters={6: lambda s: labels.index(s)} )

我不明白转换器内部的参数。

如果有人向我解释在这种情况下它是如何工作的,我将不胜感激。

谢谢!

解决方法

转换器定义了一个 lambda function,它接受​​一个参数 s。这是从文件中读取的列值(在我们的例子中是第 6 列),例如''DH''。然后将此值传递给 index 列表的 labels 函数。 ''DH'' 位于列表中的位置 1,因此该函数返回 1,然后将其存储在第 6 列的结果数组中。

示例:

import io
import numpy as np

labels = [b''NO'',b''DH'',b''SL'']

s = """0 1 2 3 4 5 NO
0 1 2 3 4 5 SL
0 1 2 3 4 5 DH"""
data = np.loadtxt(io.StringIO(s),converters={6: lambda s: labels.index(s)})
print(data)
#[[0. 1. 2. 3. 4. 5. 0.]
# [0. 1. 2. 3. 4. 5. 2.]
# [0. 1. 2. 3. 4. 5. 1.]]

请注意,如果 loadtxt 遇到不在您的列表中的值,它会失败并显示 ValueError。因此,在这种情况下最好使用 converters={6: lambda s: labels.index(s) if s in labels else np.nan} 之类的东西。

,

loadtxtgenfromtxt 都很复杂,只有基本的文档。我不得不做很多挖掘来解释(对于另一个 SO)genfromtxt 如何处理缺失值和 nan 值。 converters 也是如此。

In [279]: labels = [b''NO'',b''SL'']
     ...: txt = ''1 NO\n2 DH\n3 SL''.splitlines()
     ...: data = np.loadtxt(txt,converters={1: lambda s: labels.index(s)} )
In [280]: data
Out[280]: 
array([[1.,0.],[2.,1.],[3.,2.]])

通常将 lambda 重写为函数会有所帮助,并包含一些诊断信息。还有更多空间用于错误测试和 if/else 情况。

In [281]: def foo(astr):
     ...:     print(astr)
     ...:     return labels.index(astr)
     ...: 
In [282]: labels = [b''NO'',converters={1: foo} )
b''NO''
b''DH''
b''SL''

请注意,列值一次一个传递给 foo 作为字节字符串(b 前缀)。这就是为什么 labels 也必须是字节字符串。这是 Py2 遗留下来的,默认字符串类型是字节。

虽然 index 返回一个整数,但 loadtxt 对其应用其默认的 float dtype。我们可以将返回 dtype 更改为 int(或者更高级的结构):

In [283]: labels = [b''NO'',converters={1: foo},dtype=int)
b''NO''
b''DH''
b''SL''
In [284]: data
Out[284]: 
array([[1,0],[2,1],[3,2]])

由此可见,converters 应用于来自输入的字节字符串值,然后应用 dtype 转换。


添加不在 labels 中的字符串为我们提供了有关操作顺序的进一步线索:

In [289]: labels = [b''NO'',b''SL'']
     ...: txt = ''1 NO\n2 DH\n3 SL\n4 XX''.splitlines()
     ...: data = np.loadtxt(txt,converters={1: foo})
b''NO''
b''DH''
b''SL''
b''XX''
Traceback (most recent call last):
  File "<ipython-input-289-a3450b85790b>",line 3,in <module>
    data = np.loadtxt(txt,converters={1: foo})
  File "/usr/local/lib/python3.8/dist-packages/numpy/lib/npyio.py",line 1139,in loadtxt
    for x in read_data(_loadtxt_chunksize):
  File "/usr/local/lib/python3.8/dist-packages/numpy/lib/npyio.py",line 1067,in read_data
    items = [conv(val) for (conv,val) in zip(converters,vals)]
  File "/usr/local/lib/python3.8/dist-packages/numpy/lib/npyio.py",in <listcomp>
    items = [conv(val) for (conv,line 1126,in tobytes_first
    return conv(x.encode("latin1"))
  File "<ipython-input-281-64f4e6f34991>",in foo
    return labels.index(astr)
ValueError: b''XX'' is not in list

labels.index(b''XX") 提高了 ValueError

这个错误是在这个理解过程中出现的,它将 converters 应用到该行的所有 vals

items = [conv(val) for (conv,vals)]

对于我们未包含在 converters 中的列,loadtxt 可能添加了这样的函数:

In [297]: def bar(astr):
     ...:     print(astr)
     ...:     return astr
     ...: 
In [298]: labels = [b''NO'',b''SL'']
     ...: txt = ''1 NO\n2 DH''.splitlines()
     ...: data = np.loadtxt(txt,converters={0: bar,1: foo})
b''1''
b''NO''
b''2''
b''DH''

粗略地说,loadtxt 读取文件的一行,将其拆分为 delimiter。然后将 converters 应用于字符串列表 (vals)。

然后将这个 items 列表附加到主列表,然后执行

np.array(x,dtype)

我认为它可能逐行进行了 array 转换,但是 foo 返回字符串而不是错误时的错误消息表明 array 转换是在结束(在所有行都被“转换”之后)。

或者,它可能只收集 items 列表,并在最后用 dtype 转换一次数组。我必须检查代码以获取详细信息。

如果 dtypeNone,则需要为每列确定一个通用 dtype,并从中创建结构化数组。

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

如何解决Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案?

希望有人能在这里提供帮助。我一直在绕圈子一段时间。我只是想设置一个 python 脚本,它将一些 json 数据从 REST API 加载到云数据库中。我在 Anaconda 上设置了一个虚拟环境(因为 GCP 库推荐这样做),安装了依赖项,现在我只是尝试导入库并向端点发送请求。 我使用 Conda(和 conda-forge)来设置环境并安装依赖项,所以希望一切都干净。我正在使用带有 Python 扩展的 VS 编辑器作为编辑器。 每当我尝试运行脚本时,我都会收到以下消息。我已经尝试了其他人在 Google/StackOverflow 上找到的所有解决方案,但没有一个有效。我通常使用 IDLE 或 Jupyter 进行脚本编写,没有任何问题,但我对 Anaconda、VS 或环境变量(似乎是相关的)没有太多经验。 在此先感谢您的帮助!

  \Traceback (most recent call last):
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 22,in <module>
from . import multiarray
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\multiarray.py",line 12,in <module>
from . import overrides
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\overrides.py",line 7,in <module>
from numpy.core._multiarray_umath import (
ImportError: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
File "c:\API\citi-bike.py",line 4,in <module>
import numpy as np
File "C:\Conda\envs\gcp\lib\site-packages\numpy\__init__.py",line 150,in <module>
from . import core
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 48,in <module>
raise ImportError(msg)
ImportError:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions Failed. This error can happen for
many reasons,often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

* The Python version is: python3.9 from "C:\Conda\envs\gcp\python.exe"
* The NumPy version is: "1.21.1"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

android – setText(getString(R.strings.whatever)或setText(R.strings.whatever)?

android – setText(getString(R.strings.whatever)或setText(R.strings.whatever)?

两者都有效,显然如果你开始连接,你需要获取字符串以避免显示int.

问题:哪种“优雅”或“推荐”使用?

谢谢

解决方法

第二种方法更优雅,因为在内部,TextView(或任何View类)将完成获取指定资源的String的工作.

让组件完成内部工作总是首选.此外,它更短,更易读.

关于我所谈到的内部:如果你看一下Androids的源代码,你可以看到TextView is implemented like this的setText(int)方法:

public final void setText(int resid) {
  setText(getContext().getResources().getText(resid));
}

因此,它在内部使用Context-class从resource-id获取字符串.现在,如果你看一下getText() – 方法(也来自Context-class),你可以看到它is implemented the same way:

public final String getString(int resId) {
  return getResources().getString(resId);
}

因此,出于性能或可靠性的原因,它没有任何区别.它仍然更短,更具可读性.

cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”

cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”

如何解决cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”?

我正在尝试升级一些软件包并为现有的 Python 程序整合我的 requirements.txt,以便将其移至 docker 容器。

这个容器将基于 tensorflow docker 容器,这决定了我必须使用的一些包版本。我们在 windows 下工作,我们希望能够在我们的机器上本地运行该程序(至少在一段时间内)。所以我需要找到一个适用于 docker 和 Windows 10 的配置。

Tensorflow 2.4.1 需要 numpy~=1.19.2。使用 numpy 1.20 时,pip 会抱怨 numpy 1.20 是一个不兼容的版本。

但是在使用 numpy~=1.19.2 时,导入 cvxpy 时出现以下错误。 pip 安装所有软件包都很好:

RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd
Traceback (most recent call last):
  File "test.py",line 1,in <module>
    import cvxpy
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\__init__.py",line 18,in <module>
    from cvxpy.atoms import *
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\__init__.py",line 20,in <module>
    from cvxpy.atoms.geo_mean import geo_mean
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\geo_mean.py",in <module>
    from cvxpy.utilities.power_tools import (fracify,decompose,approx_error,lower_bound,File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\utilities\power_tools.py",in <module>
    from cvxpy.atoms.affine.reshape import reshape
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\affine\reshape.py",in <module>
    from cvxpy.atoms.affine.hstack import hstack
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\affine\hstack.py",in <module>
    from cvxpy.atoms.affine.affine_atom import AffAtom
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\affine\affine_atom.py",line 22,in <module>
    from cvxpy.cvxcore.python import canonInterface
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\cvxcore\python\__init__.py",line 3,in <module>
    import _cvxcore
ImportError: numpy.core.multiarray Failed to import

重现步骤:

1.) 在 Windows 10 下创建一个新的 Python 3.8 venv 并激活它

2.) 通过 requirements.txt 安装以下 pip install -r requirements.txt

cvxpy 
numpy~=1.19.2 # tensorflow 2.4.1 requires this version

3.) 通过 test.py

执行以下 python test.py
import cvxpy

if __name__ == ''__main__'':
    pass

如果我想使用 tensorflow 2.3,也会发生同样的事情。在这种情况下需要 numpy~=1.18,错误完全相同。

搜索错误发现很少的命中,可悲的是没有帮助我。

我该怎么做才能解决这个问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

ES6 Features 系列:Template Strings & Tagged Template Strings

ES6 Features 系列:Template Strings & Tagged Template Strings

1. Brief

  ES6 (ECMAScript 6th edition) 于 2015 年 7 月份发布,虽然各大浏览器仍未全面支持 ES6,但我们可以在后端通过 Node.js 0.12 和 io.js,而前端则通过 Traceur 或 Babel 这类 Transpiler 将 ES6 语法预转译为 ES5 语法,来提前兴奋一把。而仅需适配 IE9 + 的朋友们现在更是可以开始撸 ES6 了,而不必为学哪门 JavaScript 超集语言而烦恼。(ES6 又名为 ECMAScript 2015 或 JavaScript.next,ES4 的部分较为激进的特性被调用到该版本中实现。)

  ES6 带给我们很多惊喜,如 class、module、export 和 import 等。但在学习和运用到项目中时,我们需要注意以下两点:

  1. ES6 包含的是语法糖和语言、库的 bug fix,对工程性问题没有太大的帮助;

  2. 由于 Traceur 和 Babel 无法对 ES6 的所有特性进行完整高效的 polyfill,因此我们无法完全享用 ES6 的各项特性。

  最近接手一个项目的前端改造,正在尝试全新的技术栈 (Riot+ES6+Glup+Webpack),本系列文章将作为理论 + 项目实践的笔记供日后查阅。

 

2. What is Template Strings?

  一言以蔽之,Template Strings 就是让我们减少字符串手工拼接的工作量。

  2.1. Before ES6

// Sample 1: 单行字符串拼接
var operand1 = 1
  , operand2 = 2.1
var tpl1 = operand1 + '' + '' + operand2 + ''~='' + parseInt(operand1+operand2)
var tpl2 = [operand1, '' + '' , operand2, ''~='', parseInt(operand1 + operand2)].join('''')
// Sample 2: 多行字符串拼接
var name = ''fsjohnhuang''
  , id = ''region''
var tpl1 = ''<div id="'' + id + ''">''
  + ''<a>'' + name + ''</a>''
  + ''</div>''
var tpl2 = ''<div id=" '' + id + '' ">\
  <a>'' + name + ''</a>\
  </div>''

  2.2. Embracing ES6

// Sample 1: 单行字符串拼接
var operand1 = 1
  , operand2 = 2.1
var tpl1 = `${operand1}+${operand2}~=${parseInt(operand1+operand2)}`
// Sample 2: 多行字符串拼接
var name = ''fsjohnhuang''
  , id = ''region''
var tpl1 = `<div id="${id}">
  <a>${name}</a>
  </div>`

  假若了解过 CoffeeScript,那么会发现 ES6 的 Template Strings 怎么这么眼熟。Template Strings 由两部分组成:

    1. 模板起始符 —— `` ,称为沉音符 / 反引号 (grave accent),其内容被识别为字符串模板。

    2. 表达式占位符 —— ${<expression>} ,<expression> 为 JavaScript 的有效表达式(如 name, 1==2 等),因此 ${<expression>} 并不是简单的占位符那么简单了。

  2.3. Cautions

    1.  ${<expression>} 中可访问当前作用域所能访问到变量和函数,如

var x = 1

(function(){
  var y = 2
  (function(b){
    var tpl = `${x},${y},${a},${b}` // 结果是 "1,2,undefined,5"
  }(5))
  var a = 3
  let c = 4 // 由于采用let来声明c变量,因此不会发生variable hoist
}())

    2.  ${<expression>} 是即时计算 (real-time computing) 的,通过函数加壳可实现延迟计算 (lazy evaluation)

//real-time computing
var tpl = `${x},${y}`
var x = 1, y = 2
console.log(tpl) // "undefined, undefined"

// lazy evaluation
var tpl = ctx => `${ctx.x},${ctx.y}`
console.log(tpl({x:1, y:2})) // "1, 2"

   3. 多行陷阱 (pitfall of multiline),在编写 HTML 模板时我习惯如下写法

var tpl = ''<div>\
    <h3>${title}</h3>\
    <span>${subtitle}</span>\
  </div>''
// 然后是模板引擎解析tpl

   那现在是否就可以毫无顾虑地改用 Template Strings 呢?

var tpl = ctx => `<div>
    <h3>${ctx.title}</h3>
    <span>${ctx.subtitle}</span>
  </div>`
// 直接调用tpl函数

   答案是否定的

   原因是通过正斜杠 ( \ ) 定义的多行字符串实际输出还是一行字符串而已,但通过反引号 ( `` ) 定义的是真实的多行字符串,且通过换行符 ( \n ) 分隔每一行。

// 通过\定义多行的结果
<div>    <h3>${ctx.title}</h3>    <span>${ctx.subtitle}</span>  </div>


// 通过反引号定义多行的结果
<div>\n
    <h3>${ctx.title}</h3>\n
    <span>${ctx.subtitle}</span>\n
  </div>

  那么当使用 jQuery 将反引号定义的 HTML 模板来生产 DOM 元素时就会直接报错了,这时我们需要删除这些控制字符。

var removeCtlChar = raw => raw.replace(/[\r\n\t\v\f]/ig, '''')

 

3. What is Tagged Template Strings?

  从上文我们了解到 Template Strings 是以整体为单位进行即时计算,也就是说留给我们的自主操控能力是十分有限的。而 Tagged Template Strings 则大大增强了我们的操控欲望。

  其实 Tagged Template Strings 实质上是对 Template Strings 进行 Tokenize 操作,从而细化我们的可操作粒度。而词法类型分为 字符串表达式占位符的运算结果

var x = 1, y = 2
var tpl = ''hello${x}:${y+1}''

// Tokenize后的结果
var tokens = [''hello'', 1, '':'', 3, '''']

   具体玩法如下:

// 语法
<Tagged Function><Template Strings>

/** Sample **/
/* 定义<Tagged Function>
 * @param {Array.<DOMString>} strings - 字符串类型的tokens
 * @param {...Any} vals - 表达式占位符的运算结果tokens
 * @returns {Any}
 */
var taggedFunc = (strings, ...vals){
  var ret = []
  for(let i = 0, len = strings.length ; i < len; ++i)
    ret.push(strings.raw[i], vals[i] || '''')
  return ret
}

// 定义Template Strings
var x = 1, y =2
var ret = taggedFunc`\tHello${x}:${y+1}`
console.log(ret) // 显示 "\tHello1:3"
console.log(`\tHello${x}:${y+1}`) // 显示 "    Hello1:3"

   <Tagged Function> 函数 有两个入参分别代表两类 token。 {Array.<DOMString>} strings 为字符串类型的 tokens,而 {...Any} vals 则为表达式占位符运算结果 tokens。

   而需要注意的是: strings.length === vals.length + 1 

   另外我们看到最后两行代码会发现 `\tHello${x}:${y+1}` 中的制表符将在输出结果中起效,而经过 Tagged Function 处理的则按普通字符输出而已。其实这是通过 {Array.<DOMString>} strings.raw 属性 操作 strings 中 token 的结果,也就是说 strings.raw 属性将对控制符进行转义从而实现按照普通字符输出。

   3.1. 内置的 Tagged Function——String.raw

     其作用与上述的 taggedFunc 一样,就是将按普通字符输出 Template Strings 中的控制符。

   3.2. Cautions

     1. Tagge Template Strings 的语法是 Template Strings 紧跟在 Tagged Function 后面,两者间不能有空格或制表符等。

     2. vals 是运算后的实际值,若要延迟计算依然需要加壳。

     3. @ruanyifeng 老师说可通过 Tagged Function 来自定义带流程控制的模板语言

// 下面的hashTemplate函数
// 是一个自定义的模板处理函数
var libraryHtml = hashTemplate`
  <ul>
    #for book in ${myBooks}
      <li><i>#{book.title}</i> by #{book.author}</li>
    #end
  </ul>
`;

        本人觉得这种用法不可取,Tagged Function 本来就按照自身规则对模板进行 Tokenize,然后我们在此基础上对结果进行二次 Tokenize,那还不如直接按自己定义的规则来做词法分析更省心。

 

4. Conclusion

   Template Strings 和 Tagged Template Strings 均可通过 Traceur 和 Babel 做 transpile,所以我们现在就可以撸起了,开干吧各位!

   尊重原创,转载请注明来自:http://www.cnblogs.com/fsjohnhuang/p/4601200.html  肥子 John^_^

 

5. Thanks

    http://es6.ruanyifeng.com/#docs/string

    http://www.sitepoint.com/understanding-ecmascript-6-template-strings/

今天关于numpy.loadtxt 转换器参数,使用 b'strings'numpy str转float的分享就到这里,希望大家有所收获,若想了解更多关于Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、android – setText(getString(R.strings.whatever)或setText(R.strings.whatever)?、cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”、ES6 Features 系列:Template Strings & Tagged Template Strings等相关知识,可以在本站进行查询。

本文标签: