小编Ale*_*lex的帖子

什么是co_names?

描述co_names在检查模块读取:

局部变量名称的元组

但实际上它似乎co_names是全局变量名co_varnames的元组,而是局部变量名(和参数名)的元组.例如:

a = 1

def f(b):
    c = a + b

print(f.__code__.co_varnames)  # prints ('b', 'c')
print(f.__code__.co_names)     # prints ('a',)
Run Code Online (Sandbox Code Playgroud)

此外,在dis模块的文档中,许多指令描述意味着co_names包含全局变量的名称.例如,LOAD_GLOBAL 描述如下:

将全局命名的co_names [namei]加载到堆栈中.

我在这里误解了什么吗?是否co_names真的含有"局部变量的名字"?

编辑07/17/2017

如评论/答案中所述,这似乎是文档错误.Bug问题在这里提交.

编辑07/22/2017

拉请求修复此文档错误已批准并等待合并.

python documentation cpython

20
推荐指数
1
解决办法
3016
查看次数

如何制作一个函数作曲家

我正在尝试为我的大学学位制作一个能够完成其他功能的功能.例如,我想打电话给round_sqrt = round(sqrt) ,当我打电话给round_sqrt(5)它时,它必须显示我2而不是2.23606797749979.我在想的是这个:

def rounding(funct):
    return round(funct)
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

编辑:该函数应该只有一个参数.例如,函数的开头应该是

def rounding(func):
Run Code Online (Sandbox Code Playgroud)

所以在这个函数中,funct函数需要舍入.所以当我打电话给rounding(abs)(3.2)我看3.

python function-composition python-3.x python-decorators

20
推荐指数
3
解决办法
1362
查看次数

熊猫集团通过内存释放

问题

我注意到在迭代过程中迭代通过Pandas GroupBy对象时分配的内存不会被释放.我使用resource.getrusage(resource.RUSAGE_SELF).ru_maxrss(这篇文章的第二个答案中的详细信息)来测量Python进程使用的活动内存总量.

import resource
import gc

import pandas as pd
import numpy as np

i = np.random.choice(list(range(100)), 4000)
cols = list(range(int(2e4)))

df = pd.DataFrame(1, index=i, columns=cols)

gb = df.groupby(level=0)
# gb = list(gb)
for i in range(3):
    print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6)
    for idx, x in enumerate(gb):
        if idx == 0:
            print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6)
    # del idx, x
    # gc.collect()
Run Code Online (Sandbox Code Playgroud)

打印以下总活动内存(以gb为单位)

0.671732
1.297424
1.297952
1.923288
1.923288
2.548624
Run Code Online (Sandbox Code Playgroud)

解决方案

取消注释del idx, xgc.collect()修复问题.但是我必须del …

python memory-management python-3.x pandas

19
推荐指数
1
解决办法
2026
查看次数

在Pandas DataFrame子集(副本)上设置值很慢

import timeit
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(10, 10))

dft = df[[True, False] * 5]
# df = dft
dft2 = dft.copy()

new_data = np.random.rand(5, 10)

print(timeit.timeit('dft.loc[:, :] = new_data', setup='from __main__ import dft, new_data', number=100))
print(timeit.timeit('dft2.loc[:, :] = new_data', setup='from __main__ import dft2, new_data', number=100))
Run Code Online (Sandbox Code Playgroud)

在我的笔记本电脑上,dft(原始子集)中的设置值比dft2(深层副本dft)中的设置值慢约160倍.

为什么会这样?

编辑:删除了有关代理对象的推测.

如c.皮革建议,这可能是因为在copy(dft)与原始dataframe()上设置值时,代码路径不同dft2.

奖金问题:删除对原始DataFrame的引用df(通过取消注释该df = dft行),在我的笔记本电脑上将速度因子降低到大约2.知道为什么会这样吗?

python performance dataframe pandas

15
推荐指数
1
解决办法
1931
查看次数

将年份和年份转换为熊猫的日期时间索引

我有这个人.数据帧:

 year  doy
 2000   49   
 2000   65   
 2000   81   
 2001   97   
 2001  113   
 2001  129   
 2001  145   
 2001  161 
Run Code Online (Sandbox Code Playgroud)

我想为这个数据帧创建一个索引.索引应该是日期时间索引.这是我在做的事情:

df.index = pandas.DatetimeIndex(df['doy'].apply(lambda x: date(2000, 1, 1)+ relativedelta(days=int(x)-1)))
Run Code Online (Sandbox Code Playgroud)

但是,这会创建一个日期时间索引,该索引仅使用2000作为年份.我该如何解决这个问题?

python pandas

8
推荐指数
3
解决办法
4702
查看次数

为什么Python2.7 dict比Python3 dict使用更多的空间?

我已经读过Raymond Hettinger实现紧凑型dicts 的新方法.这解释了为什么Python 3.6中的dicts使用的内存少于Python 2.7-3.5中的dicts.但是,Python 2.7和3.3-3.5 dicts中使用的内存之间似乎存在差异.测试代码:

import sys

d = {i: i for i in range(n)}
print(sys.getsizeof(d))
Run Code Online (Sandbox Code Playgroud)
  • Python 2.7:12568
  • Python 3.5:6240
  • Python 3.6:4704

如上所述,我理解3.5和3.6之间的节省,但我很好奇节省2.7和3.5之间的原因.

python dictionary python-2.7 python-3.x python-internals

6
推荐指数
1
解决办法
282
查看次数

使用pd.read_clipboard加载DataFrame时解析日期时间

我看到很多贴在StackOverflow上的DataFrame看起来像:

          a                  dt         b
0 -0.713356 2015-10-01 00:00:00 -0.159170
1 -1.636397 2015-10-01 00:30:00 -1.038110
2 -1.390117 2015-10-01 01:00:00 -1.124016
Run Code Online (Sandbox Code Playgroud)

我仍然没有找到一种使用.read_clipboard(.read_tabledocs中的参数列表)将这些复制到我的解释器中的好方法.

我以为关键是parse_dates参数:

parse_dates : boolean or list of ints or names or list of lists or dict, default False
* boolean. If True -> try parsing the index.
* list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
* list …
Run Code Online (Sandbox Code Playgroud)

python datetime date dataframe pandas

6
推荐指数
1
解决办法
107
查看次数

将元组列表转换为允许轻松切片的数组或其他结构

使用列表推导我创建了一个看起来像的元组列表

temp = [(1, 0, 1, 0, 2), (1, 0, 1, 0, 5), (1, 0, 2, 0, 2), (1, 0, 2, 0, 5)]
Run Code Online (Sandbox Code Playgroud)

如果更容易,我也可以创建一个列表列表.

无论哪种方式,我现在想从数据中获取数组或2D列表.我可以使用切片轻松访问上面每个元组中第一个元素的值的东西

first_elements = temp[:,0]
Run Code Online (Sandbox Code Playgroud)

python

6
推荐指数
1
解决办法
64
查看次数

带有 angularjs 指令的动态标签

我想在 angularjs 中创建一个元素指令,它从作为属性传递的 json blob 生成一个 html 元素。我已经尝试了以下相当多的变体......

demoApp.directive("element", function() {
    return {
        restrict: "E",
        scope: {
            attributes: "@",
            name: "@"
        },
        template:         
            function(name, attributes) {
                var templateString = "<" + attributes.tag;
                for (attribute in attributes) {
                    if (attribute != "name_displayed" && attribute != "tag") {
                        templateString += " " + attribute + "=\"" attributes[attribute] + "\"";
                    }
                }
                templateString += " name=\"" field + "\"";
                templateString += ">";
                templateString += "</" + attributes.tag + ">";
                return attributes.name_displayed + ": …
Run Code Online (Sandbox Code Playgroud)

javascript json angularjs angularjs-directive

5
推荐指数
1
解决办法
1万
查看次数

Tensorflow和OpenCV中的双线性插值实现

我试图在tensorflowOpenCV中实现对双线性插值的处理.我的理解让我相信插值点的网格在两个库中的位置不同.这可以通过样本矩阵获得的不同结果得到证明:

import tensorflow as tf, numpy as np, cv2
a = np.arange(9, dtype=np.float32).reshape(3, 3)
cv2.resize(a, (2, 2))
Run Code Online (Sandbox Code Playgroud)

输出

array([[1. , 2.5],
       [5.5, 7. ]], dtype=float32)
Run Code Online (Sandbox Code Playgroud)

tf.InteractiveSession()
tf.image.resize_images(a[None, :, :, None], (2, 2)).eval()[0, :, :, 0]
Run Code Online (Sandbox Code Playgroud)

输出

array([[0. , 1.5],
       [4.5, 6. ]], dtype=float32)
Run Code Online (Sandbox Code Playgroud)

这个诊断是否正确?如果是这样,在张量流和OpenCV中放置插值点的方案是什么?

interpolation opencv numpy tensorflow

5
推荐指数
1
解决办法
711
查看次数