小编TMW*_*MWP的帖子

测试numpy数组中的所有值是否相等

我有一个numpy一维数组c,应该填充内容 a + b.我首先a + b在使用的设备上执行PyOpenCL.

我想c使用numpy切片快速确定python中结果数组的正确性.

这就是我现在拥有的

def python_kernel(a, b, c):
    temp = a + b
    if temp[:] != c[:]:
        print "Error"
    else:
        print "Success!"
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

ValueError:具有多个元素的数组的真值是不明确的.使用a.any()或a.all()

但似乎a.anya.all将只确定值是否不为0.

我应该怎么做,如果我想测试,如果所有的缩放器numpy阵列temp都等于在每个值numpy阵列c

python numpy

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

Python中的for循环 - 如何在循环内修改i

这段代码是用Jupyter笔记本中的Python 3.6编写的.在其他语言中,我很确定我构建了如下所示的循环:

endRw=5
lenDF=100   # 1160

for i in range(0, lenDF):
    print("i: ", i)
    endIndx = i + endRw
    if endIndx > lenDF:
                endIndx = lenDF

    print("Range to use: ", i, ":", endIndx)
    # this line is a mockup for an index that is built and used
    # in the real code to do something to a pandas DF

    i = endIndx
    print("i at end of loop", i)
Run Code Online (Sandbox Code Playgroud)

但是在测试中,i不会重置endIndx,因此循环不会构建预期的索引值.

通过构建像这样的while循环,我能够解决这个问题并得到我想要的东西:

endRw=5
lenDF=97   # 1160
i = …
Run Code Online (Sandbox Code Playgroud)

python for-loop

7
推荐指数
2
解决办法
141
查看次数

r markdown 文档 - 关于字符选项的错误,但没有看到错误

我可能在这里遗漏了一些简单的东西。当我在 R markdown 代码单元中运行代码时,它会抛出以下错误:

(*) NOTE: I saw chunk options " dataFrames, echo=TRUE eval=TRUE"
 please go to http://yihui.name/knitr/options
 (it is likely that you forgot to quote "character" options)
Run Code Online (Sandbox Code Playgroud)

以下是触发错误的单元格的代码:

```{r dataFrames, echo=TRUE eval=TRUE}

df1 <- data.frame(c(1, 2, 3),
                 c("R","S","T"),
                 c(TRUE, FALSE, TRUE))
```
Run Code Online (Sandbox Code Playgroud)

我尝试了错误中给出的链接,但没有遇到任何可以为我解释该故障的内容。有人能发现吗?

r knitr r-markdown

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

如何摆脱字符串表示周围的单引号?

此示例代码打印文件中一行的表示.它允许'\n'在一行中查看其内容,包括控制字符,因此我们将其称为行的"原始"输出.

print("%r" % (self.f.readline()))
Run Code Online (Sandbox Code Playgroud)

但是,输出显示的'是每个末尾添加的字符不在文件中.

'line of content\n'

如何摆脱输出周围的单引号?
(Python 2.7和3.6中的行为相同.)

python data-representation

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

Python 警告是在尝试警告用户之后出现的

我在目标代码中使用警告来提醒用户发生了某些事情,但不会停止代码。下面是一个基于我在实际代码中遇到的更复杂场景的简单模型:

from warnings import warn
class myClass(object):        
    def __init__(self, numberArg):

        if numberArg > 1000:
            self._tmpTxt = "That's a really big number for this code." + \
                           "Code may take a while to run..."
            warn("\n%s %s" %(numberArg, self._tmpTxt))
            print("If this were real code:")
            print("Actions code takes because this is a big number would happen here.")

        print("If this were real code, it would be doing more stuff here ...")

mc1 = myClass(1001)
Run Code Online (Sandbox Code Playgroud)

在我的实际代码中,当我实例化执行的类时__init__(self, numberArg),警告在警告之后的所有处理完成后输出。为什么会发生这种情况?

更重要的是,有没有办法确保首先输出警告,然后我的其余代码运行并提供其输出?

与此处提供的示例一样,预期的效果是在发生之前而不是之后提醒用户将要发生的事情,并像带有警告格式的警告一样提供输出。

注意:此问题是在 Windows 7 环境下在 …

python oop warnings class ipython

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

如何在没有密钥的情况下实现SQL外连接的熊猫等效

在SQL中,您可以在没有键的情况下联接两个表,以便两个表的所有记录相互合并。如果pandas.concat()or pandas.merge()或某些其他pandas语法支持此功能,则可以帮助我解决我要解决的问题的第一步。我在帮助文档中找到了一个外部联接选项,但是找不到确切的语法来执行我想要的操作(联接所有没有键的记录)。

为了更好地解释这一点:

import pandas as pd

lunchmenupairs2 = [["pizza", "italian"],["lasagna", "italian"],["orange", "fruit"]]
teamcuisinepreferences2 = [["ian", "*"]]

lunchLabels = ["Food", "Type"]
teamLabels = ["Person", "Type"]

df1 = pd.DataFrame.from_records(lunchmenupairs2, columns=lunchLabels)
df2 = pd.DataFrame.from_records(teamcuisinepreferences2, columns=teamLabels)

print(df1)
print(df2)
Run Code Online (Sandbox Code Playgroud)

输出这些表:

      Food     Type
0    pizza  italian
1  lasagna  italian
2   orange    fruit

  Person     Type
0    ian        *
Run Code Online (Sandbox Code Playgroud)

我希望合并的最终结果是:

  Person     Type Food     Type
0  ian        *   pizza     italian
1  ian        *   lasagna   italian
2  ian        *   orange    fruit
Run Code Online (Sandbox Code Playgroud)

然后,我可以轻松删除不需要的列,并转到我正在处理的代码中的下一步。这不起作用:

merged_data = pd.merge(left=df2,right=df1, how='outer') …
Run Code Online (Sandbox Code Playgroud)

python merge join dataframe

4
推荐指数
2
解决办法
1720
查看次数

更好的方法在Python中计算另一个字符串中的字符串

这段代码有效,但在这里阅读帖子我得到的印象可能不是一个非常"Pythonic"的解决方案.有没有更好的方法来解决这个特定的问题:

这段代码的作用是:它计算在另一个中找到的一个字符串的实例并返回计数.如果用户尝试传入空字符串,则会引发错误.

我提出的代码版本,但想知道是否有更好的更有效的"Pythonic"方式来做到这一点:

def count_string(raw_string, string_to_count):
    if len(string_to_count) == 0:
        raise ValueError("The length of string_to_count should not be 0!")
    else:
        str_count = 0
        string_to_count = string_to_count.lower()
        raw_string = raw_string.lower()
        if string_to_count not in raw_string:
            # this causes early exit if string not found at all
            return str_count
        else:
            while raw_string.find(string_to_count) != -1:
                indx = raw_string.find(string_to_count)
                str_count += 1
                raw_string = raw_string[(indx+1): ]
            return str_count
Run Code Online (Sandbox Code Playgroud)

此代码是用Python 2.7编写的,但应该在3.x中运行.

python coding-efficiency

2
推荐指数
1
解决办法
289
查看次数