社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

hpaulj

hpaulj 最近创建的主题
hpaulj 最近回复了
3 年前
回复了 hpaulj 创建的主题 » RuntimeWarning:在cosh--Python中遇到溢出。这是什么意思?

cosh 长得很大:

In [70]: np.cosh(2**10)
<ipython-input-70-c4511154ec1e>:1: RuntimeWarning: overflow encountered in cosh
  np.cosh(2**10)
Out[70]: inf

为什么你的 x 这么宽?在大部分范围内,这个的反比 科什 将是0。

In [72]: N=2**15; x = np.arange(-N/2,N/2)
In [73]: len(x)
Out[73]: 32768
In [74]: r = 1/(np.cosh(x)**2)
<ipython-input-74-404fbe3be390>:1: RuntimeWarning: overflow encountered in cosh
  r = 1/(np.cosh(x)**2)
<ipython-input-74-404fbe3be390>:1: RuntimeWarning: overflow encountered in square
  r = 1/(np.cosh(x)**2)
In [75]: r[:10]
Out[75]: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

In [77]: np.sum(r<1e-16)
Out[77]: 32729

看看+-20的范围 十、

In [88]: x = np.arange(-20,20)
In [89]: r = 1/(np.cosh(x)**2)
In [90]: r
Out[90]: 
array([1.69934170e-17, 1.25565312e-16, 9.27809132e-16, 6.85563373e-15,
       5.06566622e-14, 3.74304919e-13, 2.76576004e-12, 2.04363561e-11,
      ...
       1.00000000e+00, 4.19974342e-01, 7.06508249e-02, 9.86603717e-03,
       ...
       1.51005382e-10, 2.04363561e-11, 2.76576004e-12, 3.74304919e-13,
       5.06566622e-14, 6.85563373e-15, 9.27809132e-16, 1.25565312e-16])

压制警告

In [148]: x=np.array([-2**15,-2**4,0,2**4,2**15])

In [155]: np.cosh(x)
<ipython-input-155-1e743139b88e>:1: RuntimeWarning: overflow encountered in cosh
  np.cosh(x)
Out[155]: 
array([           inf, 4.44305526e+06, 1.00000000e+00, 4.44305526e+06,
                  inf])
In [156]: 1/(np.cosh(x)**2)
<ipython-input-156-5cf76600c0c7>:1: RuntimeWarning: overflow encountered in cosh
  1/(np.cosh(x)**2)
Out[156]: 
array([0.00000000e+00, 5.06566622e-14, 1.00000000e+00, 5.06566622e-14,
       0.00000000e+00])

该警告不会阻止您获取有用的值。这是一个 警告 ,而不是 错误 .

但可以抑制警告。在路上是和 errstate :

In [157]: with np.errstate(over='ignore'):
     ...:     y = 1/(np.cosh(x)**2)
     ...: 
In [158]: y
Out[158]: 
array([0.00000000e+00, 5.06566622e-14, 1.00000000e+00, 5.06566622e-14,
       0.00000000e+00])

np.seterr 也可以使用,但它将改变整个脚本的处理方式,而不仅仅是这个上下文。所以 with np.errstate 优先考虑。

一定要花时间阅读文档。

In [159]: np.geterr()
Out[159]: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

还有一个 warnings 单元

Why can't I suppress numpy warnings

因此,您的数据框显示为:

In [161]: df
Out[161]: 
   Y              X
0  1  [[0,1],[0,1]]
1  0  [[1,0],[1,0]]

虽然这并没有显示字符串引号。

In [162]: df['Y'].values
Out[162]: array([1, 0])

这个 X 列是字符串的1d数组,对象数据类型:

In [163]: df['X'].values
Out[163]: array(['[[0,1],[0,1]]', '[[1,0],[1,0]]'], dtype=object)

在评估中, values 现在是一系列列表:

In [164]: from ast import literal_eval
In [165]: df['X'].apply(literal_eval)
Out[165]: 
0    [[0, 1], [0, 1]]
1    [[1, 0], [1, 0]]
Name: X, dtype: object
In [166]: df['X'].apply(literal_eval).values
Out[166]: array([list([[0, 1], [0, 1]]), list([[1, 0], [1, 0]])], dtype=object)

但如果我们将其提取为一个列表:

In [168]: df['X'].apply(literal_eval).to_list()
Out[168]: [[[0, 1], [0, 1]], [[1, 0], [1, 0]]]

我们可以很容易地将其转化为一个数组:

In [169]: np.array(_)
Out[169]: 
array([[[0, 1],
        [0, 1]],

       [[1, 0],
        [1, 0]]])

回到数组形式,我们可以使用 stack

In [170]: np.stack(df['X'].apply(literal_eval).values)
Out[170]: 
array([[[0, 1],
        [0, 1]],

       [[1, 0],
        [1, 0]]])

堆栈 就像 concatenate vstack 除了它增加了一个维度,表现得更像 np.array .

现在,tensorflow转换应该可以工作了。

你的第二个 apply ,仅将列表数组更改为数组数组。

In [174]: df['X'].apply(literal_eval).apply(np.array).values
Out[174]: 
array([array([[0, 1],
              [0, 1]]), array([[1, 0],
                               [1, 0]])], dtype=object)

np.stack 这方面也很有效。

3 年前
回复了 hpaulj 创建的主题 » python numpy中的组合数学

直接使用python itertools:

In [134]: import itertools
In [135]: a,b = [1,2,3], [4,5,6]
In [137]: list(itertools.product(a,b))
Out[137]: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

或作为数组:

In [145]: np.array(list(itertools.product(a,b)))
Out[145]: 
array([[1, 4],
       [1, 5],
       [1, 6],
       [2, 4],
       [2, 5],
       [2, 6],
       [3, 4],
       [3, 5],
       [3, 6]])
3 年前
回复了 hpaulj 创建的主题 » 用Numpy Python编写数组

你要做的应该是列表和数组。

In [163]: a = [2323,34,12,-23,12,4,-33,-2,-1,11,-2]
     ...: b = [12,-23-1,-1,-3,-12]
     ...: c = np.array([23,45,3,13,-1992,5])

收集列表中的变量:

In [164]: alist = [a,b,c]
In [165]: alist
Out[165]: 
[[2323, 34, 12, -23, 12, 4, -33, -2, -1, 11, -2],
 [12, -24, -1, -3, -12],
 array([   23,    45,     3,    13, -1992,     5])]

如果我像你一样迭代,并给 item ,没有任何变化 alist .

In [166]: for item in alist:
     ...:     item = [1,2,3]
     ...: 
In [167]: alist
Out[167]: 
[[2323, 34, 12, -23, 12, 4, -33, -2, -1, 11, -2],
 [12, -24, -1, -3, -12],
 array([   23,    45,     3,    13, -1992,     5])]

这是至关重要的;在遍历列表时,不能替换迭代变量;否则,您将失去与源的连接。

相反,我们修改了 项目 ,将其更改到位。

In [168]: for item in alist:
     ...:     for i,v in enumerate(item):
     ...:         if v<0:
     ...:             item[i] = 0
     ...: 
     ...: 

现在,更改出现在列表中:

In [169]: alist
Out[169]: 
[[2323, 34, 12, 0, 12, 4, 0, 0, 0, 11, 0],
 [12, 0, 0, 0, 0],
 array([23, 45,  3, 13,  0,  5])]

验证这是否已更改原始列表/阵列:

In [170]: a
Out[170]: [2323, 34, 12, 0, 12, 4, 0, 0, 0, 11, 0]

让我们尝试一些更接近您的代码的东西:

In [171]: format_number = lambda n: n if n % 1 else int(n)
In [174]: formater = [2323,34,12,-23,12,4,-33,-2,-1,11,-2]
In [175]: new = list(map(lambda n: 0 if n < 0 else format_number(n), formater))
In [176]: new
Out[176]: [2323, 34, 12, 0, 12, 4, 0, 0, 0, 11, 0]

使用列表(map())我创建了一个新列表。如果你想在循环中使用这个,就像我在 项目 ,我必须修改原文。

In [177]: formater[:] = new
In [178]: formater
Out[178]: [2323, 34, 12, 0, 12, 4, 0, 0, 0, 11, 0]

将其应用于原始变量:

In [179]: a = [2323,34,12,-23,12,4,-33,-2,-1,11,-2]
     ...: b = [12,-23-1,-1,-3,-12]
     ...: c = np.array([23,45,3,13,-1992,5])
In [180]: alist = [a,b,c]
In [181]: for item in alist:
     ...:     item[:]=list(map(lambda n: 0 if n < 0 else format_number(n), item))
     ...: 
In [182]: alist
Out[182]: 
[[2323, 34, 12, 0, 12, 4, 0, 0, 0, 11, 0],
 [12, 0, 0, 0, 0],
 array([23, 45,  3, 13,  0,  5])]
3 年前
回复了 hpaulj 创建的主题 » 在Python中创建数组nx1?

MATLAB代码生成一个(1,n)大小的矩阵,该矩阵被转换为(n,1)

>> 2:5
ans =

   2   3   4   5

>> (2:5)'
ans =

   2
   3
   4
   5

MATLAB矩阵总是2d(或更高)。 numpy 阵列可以是1d甚至0d。

https://numpy.org/doc/stable/user/numpy-for-matlab-users.html

在里面 努比 :

arange 生成1d阵列:

In [165]: np.arange(2,5)
Out[165]: array([2, 3, 4])
In [166]: _.shape
Out[166]: (3,)

向数组中添加尾随维度的方法有多种:

In [167]: np.arange(2,5)[:,None]
Out[167]: 
array([[2],
       [3],
       [4]])
In [168]: np.arange(2,5).reshape(3,1)
Out[168]: 
array([[2],
       [3],
       [4]])
 

努比 有一个转置,但它在一维数组中的行为并不是人们对二维数组的期望。它实际上比MATLAB更强大、更通用 ' .

5 年前
回复了 hpaulj 创建的主题 » 在两个ndarray之间执行广播二进制操作的Pythonic方法

两个输入数组必须扩展为:

(N1, N2_1)     => (N1, N2_1, 1)
(N1, N2_2)     => (N1, 1,    N2_2)
(N1, N2_1, N2_2)

例如

A1[:, :, None] * A2[:, None, :]

同样地:

(N1, N2, N3_1)
(N1, N2, N3_2)
(N1, N2, N3_1, N3_2)

A1[...,None] * A2[:,:,None,:]

完整的回溯就好了。我猜是的 seaborn.distplot 正在使用 scipy.stats 计算某事。错误发生在

def _compute_qth_percentile(sorted, per, interpolation_method, axis):
    ....
    indexer = [slice(None)] * sorted.ndim
    ...
    indexer[axis] = slice(i, i + 2)
    ...
    return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval

所以在最后一行,列表 indexer 用于切片 sorted .

In [81]: x = np.arange(12).reshape(3,4)
In [83]: indexer = [slice(None), slice(None,2)]
In [84]: x[indexer]
/usr/local/bin/ipython3:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
  #!/usr/bin/python3
Out[84]: 
array([[0, 1],
       [4, 5],
       [8, 9]])
In [85]: x[tuple(indexer)]
Out[85]: 
array([[0, 1],
       [4, 5],
       [8, 9]])

使用切片列表是可行的,但计划是在将来贬值。涉及多个维度的索引应该是元组。在上下文中使用列表是一种正在逐步淘汰的旧样式。

所以 scipy 开发人员需要解决这个问题。这不是最终用户必须面对的问题。但现在,不要担心 futurewarning . 它不影响计算或绘图。有一种方法可以压制未来的警告,但我不太清楚。

FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use `arr[tuple(seq)]` instead of `arr[seq]`

只需获取所有值。给你一个元组列表。 np.array() 返回到原始数组:

In [12]: cursor.execute('SELECT * from data')
Out[12]: <sqlite3.Cursor at 0xaf8e9d60>
In [13]: alist = cursor.fetchall()
In [14]: len(alist)
Out[14]: 100
In [15]: alist[0]
Out[15]: 
(0.3327498114993416,
 0.6164620040846208,
 0.5099007559772143,
 0.7808234554641948)
In [16]: data1 = np.array(alist)
In [17]: np.allclose(data, data1)
Out[17]: True

这是一个元组列表并不重要。就像一张单子一样好。

6 年前
回复了 hpaulj 创建的主题 » python:从3d numpy数组中的2d数组访问保存的点

你的问题有些含糊,但我认为你想这样做:

In [2]: arr = np.arange(24).reshape(4,3,2)                                      
In [3]: levels = np.random.randint(0,4,(3,2))                                   
In [4]: levels                                                                  
Out[4]: 
array([[1, 2],
       [3, 1],
       [0, 2]])
In [5]: arr                                                                     
Out[5]: 
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]],

       [[12, 13],
        [14, 15],
        [16, 17]],

       [[18, 19],
        [20, 21],
        [22, 23]]])
In [6]: arr[levels, np.arange(3)[:,None], np.arange(2)]                         
Out[6]: 
array([[ 6, 13],
       [20,  9],
       [ 4, 17]])

levels IS(3,2)。我创建了另外两个索引数组,它们用它(3,1)和(2,)广播。结果是一个(3,2)数组 arr ,由它们的组合索引选择。

6 年前
回复了 hpaulj 创建的主题 » python:向实例添加属性,使其出现在类中

以八度为例 https://octave.org/doc/v4.4.1/Structure-Arrays.html

生成结构数组:

>> x(1).a = "string1";
>> x(2).a = "string2";
>> x(1).b = 1;
>> x(2).b = 2;
>>
>> x
x =

  1x2 struct array containing the fields:

    a
    b

如果向一个条目添加字段,则会为另一个条目添加或定义默认值:

>> x(1).c = 'red'
x =

  1x2 struct array containing the fields:

    a
    b
    c

>> x(2)
ans =

  scalar structure containing the fields:

    a = string2
    b =  2
    c = [](0x0)

>> save -7 struct1.mat x

麻木的

In [549]: dat = io.loadmat('struct1.mat')
In [550]: dat
Out[550]: 
{'__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.2.2, 2019-02-09 18:42:35 UTC',
 '__version__': '1.0',
 '__globals__': [],
 'x': ...

In [551]: dat['x']
Out[551]: 
array([[(array(['string1'], dtype='<U7'), array([[1.]]), array(['red'], dtype='<U3')),
        (array(['string2'], dtype='<U7'), array([[2.]]), array([], shape=(0, 0), dtype=float64))]],
      dtype=[('a', 'O'), ('b', 'O'), ('c', 'O')])
In [552]: _.shape
Out[552]: (1, 2)

该结构已转换为结构化的numpy数组,具有相同的 shape 作为八度音阶 size(x) . 每个struct字段都是 dat .

与Octave/Matlab相比,我们不能在 dat['x'] 就位。我认为在 import numpy.lib.recfunctions as rf 它可以添加一个字段,对未定义的值使用各种形式的屏蔽或默认值,但这将生成一个新数组。有了一些工作,我可以从头开始。

In [560]: x1 = rf.append_fields(x, 'd', [10.0])
In [561]: x1
Out[561]: 
masked_array(data=[(array(['string1'], dtype='<U7'), array([[1.]]), array(['red'], dtype='<U3'), 10.0),
                   (array(['string2'], dtype='<U7'), array([[2.]]), array([], shape=(0, 0), dtype=float64), --)],
             mask=[(False, False, False, False),
                   (False, False, False,  True)],
       fill_value=('?', '?', '?', 1.e+20),
            dtype=[('a', 'O'), ('b', 'O'), ('c', 'O'), ('d', '<f8')])
In [562]: x1['d']
Out[562]: 
masked_array(data=[10.0, --],
             mask=[False,  True],
       fill_value=1e+20)

这种操作不适合python类系统。类通常不会跟踪其实例。一旦定义了一个类,它通常不会被修改。可以维护实例列表,也可以向现有类添加方法,但这不是常见的做法。

6 年前
回复了 hpaulj 创建的主题 » 在对多维数组求和时理解python的“冒号运算符”

假设 depth , r c 是鳞片,那么

dout[depth, r, c]

是标量(如果 dout 是3D)

dout[depth, r, c] * w[depth,:,:,:]

w[depth, :, :, :] 是从 w ,即,由 深度 索引。这只是标量乘以子数组中的每个元素,生成一个新数组。

dx[:,r:H,c:W] += dout[depth, r, c] * w[depth,:,:,:]

有效地:

dx[:,r:H,c:W] = dx[:, r:H, c:W] + dout[depth, r, c] * w[depth,:,:,:]

dx[:, r:H, c:W] 是一片 dx 类3D DX 而是沿着第二和第三轴的一个子集。如果切片是正确的,它的形状应该与 w[depth, :,:,:]

我看不到任何花哨的广播或特别行动。它只是从每个数组中提取匹配的大小部分,添加它们并将值放回正确的块中 DX .

颜色运算符只是基本的numpy索引运算符。


dx.shape  (channels, height, width)
dout.shape  (num, m , k)
w.shape   (num, channels, height, width)

有了三维索引, dout[depth, r, c] 形状 杜特 没关系。这只是一个值。

In [295]: 10 * np.arange(12).reshape(3,4)
Out[295]: 
array([[  0,  10,  20,  30],
       [ 40,  50,  60,  70],
       [ 80,  90, 100, 110]])

与标量相乘可以被认为是与充满该值的匹配数组相乘

In [297]: np.full((3,4),10)
Out[297]: 
array([[10, 10, 10, 10],
       [10, 10, 10, 10],
       [10, 10, 10, 10]])

广播规则使得做同样的事情成为可能,但是使用1d、2d或其他大小的数组。但我在你的例子中看不到这种情况,我在这里就不谈了。

In [71]: txt = '''16.37.235.153|119.222.242.130|38673|161|17|62|4646|
    ...: 16.37.235.153|119.222.242.112|56388|161|17|62|4646|
    ...: 16.37.235.200|16.37.235.153|59009|514|17|143|21271|
    ...: '''

encoding 警告令人讨厌,但并不重要。

当dtype=none时,应该得到一个结构化数组 field 每列:

In [74]: data = np.genfromtxt(txt.splitlines(), encoding=None, dtype=None,delimiter='|')
In [75]: data
Out[75]: 
array([('16.37.235.153', '119.222.242.130', 38673, 161, 17,  62,  4646, False),
       ('16.37.235.153', '119.222.242.112', 56388, 161, 17,  62,  4646, False),
       ('16.37.235.200', '16.37.235.153', 59009, 514, 17, 143, 21271, False)],
      dtype=[('f0', '<U13'), ('f1', '<U15'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8'), ('f5', '<i8'), ('f6', '<i8'), ('f7', '?')])

这是1D。

作为列表(或元组)的列表

In [76]: data.tolist()
Out[76]: 
[('16.37.235.153', '119.222.242.130', 38673, 161, 17, 62, 4646, False),
 ('16.37.235.153', '119.222.242.112', 56388, 161, 17, 62, 4646, False),
 ('16.37.235.200', '16.37.235.153', 59009, 514, 17, 143, 21271, False)]

好像是在填写最后一个字段(在最后一个字段之后 | )使用布尔值 False . 也许可以用一些 filling 参数。

或者限制usecols来省略它

In [77]: data = np.genfromtxt(txt.splitlines(), encoding=None, dtype=None,delimiter='|',u
    ...: secols=range(7))
In [78]: data
Out[78]: 
array([('16.37.235.153', '119.222.242.130', 38673, 161, 17,  62,  4646),
       ('16.37.235.153', '119.222.242.112', 56388, 161, 17,  62,  4646),
       ('16.37.235.200', '16.37.235.153', 59009, 514, 17, 143, 21271)],
      dtype=[('f0', '<U13'), ('f1', '<U15'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8'), ('f5', '<i8'), ('f6', '<i8')])
6 年前
回复了 hpaulj 创建的主题 » python argparse:增加参数和描述之间的空间

当前 HelpFormatter 是否检查 os.environ['COLUMNS'] 用于终端宽度。但这不会动态更新,甚至可能无法设置。

有一个补丁

https://bugs.python.org/file24602/issue13041.patch argparse: terminal width is not detected properly

这显然是最近放进3.8的,看 shutil.get_terminal_size().columns 相反。


至于为什么 argparse 不提供更直接的宽度控制-设计理念已允许自定义 formatter_class 规范,而不是一组(可能)大的格式化参数。大多数参数 ArgumentParser 与解析有关,而不是帮助格式化。其目标是允许完全定制,而不会将输入与许多很少使用的参数混淆。

这个 帮助格式化程序 类不接受几个关键字参数:

HelpFormatter.__init__(self, prog, indent_increment=2, max_help_position=24, width=None)

但是,当前创建格式化程序的方法只是通过 prog 参数。

Giacomo的答案显示了如何指定这些其他参数:

formatter = lambda prog: argparse.HelpFormatter(prog,max_help_position=52)

你也可以子类 帮助格式化程序 自定义格式。这就是备选方案喜欢的 RawTextHelpFormatter 做。

有关自定义格式化程序的详细信息

从argparse文档中:

格式化程序类

ArgumentParser对象允许通过指定备用格式类自定义帮助格式。目前,这类课程有四个:

提供并列出这4个类并不意味着有限制。其他定制是允许的,甚至是鼓励的。

https://bugs.python.org/issue13023 ,史蒂文·贝萨德,原作者 argparse ,提倡编写自己的格式化程序类:

您的解决方案实际上是当前推荐的解决方案——将两个您想要组合的类混合在一起,并将子类作为参数传递。这可能会被记录在某个地方(并测试更多)。

他说的混合是:

class myFormatter(argparse.RawDescriptionHelpFormatter,
                  argparse.ArgumentDefaultsHelpFormatter):
    pass

我提到了 max_help_position 3年前:

https://bugs.python.org/issue25297 max_help_position is not works in argparse library

还有一个问题:

max_help_position is not works in python argparse library

中的其他示例 argparse 允许您提供自定义类或函数的地方包括:

https://docs.python.org/3/library/argparse.html#action-classes https://docs.python.org/3/library/argparse.html#the-namespace-object https://docs.python.org/3/library/argparse.html#customizing-file-parsing https://docs.python.org/3/library/argparse.html#type

我不会担心 最大帮助位置 参数消失或被禁用。如果我在这件事上有任何发言权,像这样的任何提议的变更都将被拒绝,理由是它可能存在向后兼容性问题。

在实践中,最容易更改文档以匹配代码,或者更好地说明模糊的点。在这种情况下, lambda 呼叫 帮助格式化程序 可以被记录下来。我还可以想象定义一个执行相同操作的小函数。在不可能伤害现有用户的情况下,添加功能是最简单的。

6 年前
回复了 hpaulj 创建的主题 » python-在具有相同“外部”大小的数组之间广播

你有一个(2,2,3)和一个(2,1)。第二个扩展到(1,2,1)(前面的自动新轴),然后扩展到(2,2,3)。

尝试 b[:,:,None] 使之(2,1,1)。

6 年前
回复了 hpaulj 创建的主题 » 如何将numpy datetime64[ns]转换为python datetime?

我想知道你是否需要所有这些转换工作。使用正确的时间单位A datetime64 可以生成 datetime 直接对象。

我不确定你的 when 变量,但假设它来自 pandas 就像一个 DatetimeIndex :

In [56]: time = pandas.date_range('6/28/2013', periods=5, freq='5D')
In [57]: time
Out[57]: 
DatetimeIndex(['2013-06-28', '2013-07-03', '2013-07-08', '2013-07-13',
               '2013-07-18'],
              dtype='datetime64[ns]', freq='5D')

等效numpy数组

In [58]: time.values
Out[58]: 
array(['2013-06-28T00:00:00.000000000', '2013-07-03T00:00:00.000000000',
       '2013-07-08T00:00:00.000000000', '2013-07-13T00:00:00.000000000',
       '2013-07-18T00:00:00.000000000'], dtype='datetime64[ns]')
In [59]: time.values.tolist()
Out[59]: 
[1372377600000000000,
 1372809600000000000,
 1373241600000000000,
 1373673600000000000,
 1374105600000000000]

[ns] 结果是一个大整数,某种类型的“时间戳”。但如果我将时间单位转换为秒,甚至是微秒(us):

In [60]: time.values.astype('datetime64[s]')
Out[60]: 
array(['2013-06-28T00:00:00', '2013-07-03T00:00:00',
       '2013-07-08T00:00:00', '2013-07-13T00:00:00',
       '2013-07-18T00:00:00'], dtype='datetime64[s]')
In [61]: time.values.astype('datetime64[s]').tolist()
Out[61]: 
[datetime.datetime(2013, 6, 28, 0, 0),
 datetime.datetime(2013, 7, 3, 0, 0),
 datetime.datetime(2013, 7, 8, 0, 0),
 datetime.datetime(2013, 7, 13, 0, 0),
 datetime.datetime(2013, 7, 18, 0, 0)]

结果是 日期时间 物体。

6 年前
回复了 hpaulj 创建的主题 » 有没有办法让python all()函数处理多维数组?
Signature: all(iterable, /)
Docstring:
Return True if bool(x) is True for all values x in the iterable.

对于一维数组:

In [200]: x=np.ones(3)                                                               
In [201]: x                                                                          
Out[201]: array([1., 1., 1.])
In [202]: y = x==x                                                                   
In [203]: y          # 1d array of booleans                                                                      
Out[203]: array([ True,  True,  True])
In [204]: bool(y[0])                                                                 
Out[204]: True
In [205]: all(y)                                                                     
Out[205]: True

对于二维数组:

In [206]: x=np.ones((2,3))                                                           
In [207]: x                                                                          
Out[207]: 
array([[1., 1., 1.],
       [1., 1., 1.]])
In [208]: y = x==x                                                                   
In [209]: y                                                                          
Out[209]: 
array([[ True,  True,  True],
       [ True,  True,  True]])
In [210]: y[0]                                                                       
Out[210]: array([ True,  True,  True])
In [211]: bool(y[0])                                                                 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-211-d0ce0868392c> in <module>
----> 1 bool(y[0])

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

但对于不同的二维阵列:

In [212]: x=np.ones((3,1))                                                           
In [213]: y = x==x                                                                   
In [214]: y                                                                          
Out[214]: 
array([[ True],
       [ True],
       [ True]])
In [215]: y[0]                                                                       
Out[215]: array([ True])
In [216]: bool(y[0])                                                                 
Out[216]: True
In [217]: all(y)                                                                     
Out[217]: True

对numpy数组的迭代发生在第一个维度上。 [i for i in x]

每当在需要标量布尔值的上下文中使用多值布尔值数组时,都会引发此歧义值错误。 if or/and 表达式是常见的。

In [223]: x=np.ones((2,3))                                                           
In [224]: y = x==x                                                                   
In [225]: np.all(y)                                                                  
Out[225]: True

np.all 是不同的巨蟒 all 因为它“知道”尺寸。在这种情况下,它会 ravel 要将数组视为1d:

缺省值(默认值) axis = None )是对输入数组的所有维度执行逻辑和。

 File "/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 974, in from_dict
    if isinstance(list(data.values())[0], (Series, dict)):

TypeError: 'numpy.ndarray' object is not callable

如果 data 是一个数据帧,它将产生此错误,因为 value 是数组,而不是函数。见DF文件:

DataFrame.values
Return a Numpy representation of the DataFrame.

什么 from_dict Expires是一个字典,它确实有一个 values 方法。

pd.DataFrame.from_dict(df, orient='index')

因此,如果 df 创建为字典,但在下一个循环失败时 东风 是一个数据帧(从最后一个循环结束)。