我似乎找到了一个陷阱,使用.sum()的numpy数组,但我无法找到一个解释.从本质上讲,如果我尝试总结大阵,然后我开始变得无厘头的答案,但这种情况发生默默,我不能使输出足够好,谷歌的事业感.
例如,这与预期完全一样:
a = sum(xrange(2000))
print('a is {}'.format(a))
b = np.arange(2000).sum()
print('b is {}'.format(b))
Run Code Online (Sandbox Code Playgroud)
为两者提供相同的输出:
a is 1999000
b is 1999000
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用:
c = sum(xrange(200000))
print('c is {}'.format(c))
d = np.arange(200000).sum()
print('d is {}'.format(d))
Run Code Online (Sandbox Code Playgroud)
给出以下输出:
c is 19999900000
d is -1474936480
Run Code Online (Sandbox Code Playgroud)
在更大的阵列上,可以获得积极的结果.这更加阴险,因为我可能不会发现一些不寻常的事情正在发生.例如:
e = sum(xrange(100000000))
print('e is {}'.format(e))
f = np.arange(100000000).sum()
print('f is {}'.format(f))
Run Code Online (Sandbox Code Playgroud)
给出这个:
e is 4999999950000000
f is 887459712
Run Code Online (Sandbox Code Playgroud)
我猜这是与数据类型有关,甚至使用python float似乎解决了这个问题:
e = sum(xrange(100000000))
print('e is {}'.format(e))
f = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Python 3,6中的max函数:
print('Maximum is:', max(1, 3, 2, 5, 4))
Run Code Online (Sandbox Code Playgroud)
结果是
File "E:/ProgramyRobione/untitled1.py", line 2, in <module>
print('Maximum is:', max(1, 3, 2, 5, 4))
TypeError: 'int' object is not callable
Run Code Online (Sandbox Code Playgroud)
我正在使用Spyder,那条线就是代码应该做的.
我正在分析我的一些代码,发现一个让我感到惊讶的结果np.where().我想where()在我的数组切片上使用(知道2D数组的很大一部分与我的搜索无关),并发现它是我的代码中的瓶颈.作为测试,我创建了一个新的2D数组作为该切片的副本并测试了它的速度where().事实证明它运行得快得多.在我的实际情况中,速度提升非常重要,但我认为这个测试代码仍然证明了我的发现:
import numpy as np
def where_on_view(arr):
new_arr = np.where(arr[:, 25:75] == 5, arr[:, 25:75], np.NaN)
def where_on_copy(arr):
copied_arr = arr[:, 25:75].copy()
new_arr = np.where(copied_arr == 5, copied_arr, np.NaN)
arr = np.random.choice(np.arange(10), 1000000).reshape(1000, 1000)
Run Code Online (Sandbox Code Playgroud)
而timeit结果:
%timeit where_on_view(arr)
398 µs ± 2.82 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit where_on_copy(arr)
295 µs ± 6.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops …Run Code Online (Sandbox Code Playgroud) 基本上我需要从一串数据创建一个字典
鉴于:
data = "electron1, gamma5, proton43, boson98, ..."
Run Code Online (Sandbox Code Playgroud)
d(data) 会导致:
{'electron':1, 'gamma':5, 'proton':43, 'boson':98, ...}
Run Code Online (Sandbox Code Playgroud)
我当前的代码显示"基数10 ..."的错误消息
def d(n):
pair = dict()
for i in range(0,n):
word = input().split()
key = word[0]
value = word[1]
pair[key]=value
print(pair)
n = int(input())
d ={}
for i in range(n):
text = input().split()
d[text[0]] = text[1]
print(d)
Run Code Online (Sandbox Code Playgroud) 我有这个 df:
Name num1 num2 num3
A 1 2 3
B 4 5 6
C 7 8 9
Run Code Online (Sandbox Code Playgroud)
我的目标是将每一行除以总数。这就是我想出的:
df.loc[:,"num1":"num3"] = df.loc[:,"num1":"num3"].div(df["total"], axis=0)
Run Code Online (Sandbox Code Playgroud)
效果很好。但是,如果在 num3 之后添加了更多“numx”列,我将不得不手动将代码更新为“num1”:“numx”。有办法解决这个问题吗?
我是一名试图进入 Python 的 R 程序员。在 R 中,当我想有条件地改变一列时,我使用:
col = dplyr::mutate(col, ifelse(condition, if_true(x), if_false(x))
Run Code Online (Sandbox Code Playgroud)
在 Python 中,如何有条件地改变列值?这是我的最小可重复示例:
def act(cntnt):
def do_thing(cntnt):
return(cntnt + "has it")
def do_other_thing(cntnt):
return(cntnt + "nope")
has_abc = cntnt.str.contains.contains("abc")
if has_abc == T:
cntnt[has_abc].apply(do_thing)
else:
cntnt[has_abc].apply(do_other_thing)
Run Code Online (Sandbox Code Playgroud) 假设我有数组a和b
a = np.array([1,2,3])
b = np.array(['red','red','red'])
Run Code Online (Sandbox Code Playgroud)
如果我要对这些数组应用一些像这样的花哨索引
b[a<3]="blue"
Run Code Online (Sandbox Code Playgroud)
我得到的输出是
array(['blu', 'blu', 'red'], dtype='<U3')
Run Code Online (Sandbox Code Playgroud)
我知道这个问题是因为 numpy 最初只为 3 个字符分配空间,因此它无法将整个单词 blue 放入数组中,我可以使用什么解决方法?
目前我正在做
b = np.array([" "*100 for i in range(3)])
b[a>2] = "red"
b[a<3] = "blue"
Run Code Online (Sandbox Code Playgroud)
但这只是一种解决方法,这是我的代码中的错误吗?或者是numpy的一些问题,我该如何解决这个问题?
将参数传递给 apscheduler 处理函数 这对我来说不起作用,我尝试了不同的语法变体(见下文)。我可能会遗漏一些更基本的东西。
@app.route("/tick", methods=['GET', 'POST'])
def tick(datetimes, texti):
flash('DO! Sir, you have planned on the {} this:'.format(datetimes), 'success')
flash(texti, 'info')
return redirect(url_for('td_list'))
def Schedule_reminders():
with app.test_request_context():
if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
# /sf/ask/661437101/
scheduler = BackgroundScheduler()
tds = Td.query.all()
for td in tds:
run_date = td.date +' '+ td.time +':00'
# /sf/ask/868889591/#39027779
datetimes = run_date
texti = td.text
#scheduler.add_job(tick, 'date', [datetimes, texti], run_date)
# ValueError: dictionary update sequence element #0 has length 1; 2 is required
#scheduler.add_job(lambda: tick(datetimes, texti), …Run Code Online (Sandbox Code Playgroud) 当我尝试为 python 安装 mysql 包时出现此错误:
C:\Windows\system32>pip install mysql
Collecting mysql
Using cached https://files.pythonhosted.org/packages/bf/5f/b574ac9f70811df0540e403309f349a8b9fa1a25d3653824c32e52cc1f28/mysql-0.0.2.tar.gz
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz
Installing collected packages: mysqlclient, mysql
Running setup.py install for mysqlclient ... error
ERROR: Command errored out with exit status 1:
command: 'c:\program files (x86)\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Uros\\AppData\\Local\\Temp\\pip-install-67_bzzjm\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\Uros\\AppData\\Local\\Temp\\pip-install-67_bzzjm\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Uros\AppData\Local\Temp\pip-record-wbot1jpz\install-record.txt' --single-version-externally-managed --compile
cwd: C:\Users\Uros\AppData\Local\Temp\pip-install-67_bzzjm\mysqlclient\
Complete output (24 lines):
running install
running build
running build_py
creating build
creating build\lib.win32-3.8
creating build\lib.win32-3.8\MySQLdb …Run Code Online (Sandbox Code Playgroud) 我想生成对称零对角矩阵。我的对称部分工作,但是当我使用 numpy 的 fill_diagonal 作为结果时,我得到了“无”。我的代码如下。感谢您阅读
import numpy as np
matrix_size = int(input("Size of the matrix \n"))
random_matrix = np.random.random_integers(-4,4,size=(matrix_size,matrix_size))
symmetric_matrix = (random_matrix + random_matrix.T)/2
print(symmetric_matrix)
zero_diogonal_matrix = np.fill_diagonal(symmetric_matrix,0)
print(zero_diogonal_matrix)
Run Code Online (Sandbox Code Playgroud) python ×10
numpy ×4
pandas ×2
apscheduler ×1
args ×1
arrays ×1
conditional ×1
division ×1
flask ×1
function ×1
if-statement ×1
mysql ×1
python-2.7 ×1
python-3.x ×1
row ×1
spyder ×1