在对Pandas(0.17.1)DataFrame上的各种类型的查找进行实验时,我只剩下几个问题.
这是设置......
import pandas as pd
import numpy as np
import itertools
letters = [chr(x) for x in range(ord('a'), ord('z'))]
letter_combinations = [''.join(x) for x in itertools.combinations(letters, 3)]
df1 = pd.DataFrame({
'value': np.random.normal(size=(1000000)),
'letter': np.random.choice(letter_combinations, 1000000)
})
df2 = df1.sort_values('letter')
df3 = df1.set_index('letter')
df4 = df3.sort_index()
Run Code Online (Sandbox Code Playgroud)
所以df1看起来像这样......
print(df1.head(5))
>>>
letter value
0 bdh 0.253778
1 cem -1.915726
2 mru -0.434007
3 lnw -1.286693
4 fjv 0.245523
Run Code Online (Sandbox Code Playgroud)
以下是测试查找性能差异的代码...
print('~~~~~~~~~~~~~~~~~NON-INDEXED LOOKUPS / UNSORTED DATASET~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
%timeit df1[df1.letter == 'ben']
%timeit df1[df1.letter == 'amy'] …
Run Code Online (Sandbox Code Playgroud) 我正在尝试自学Python的异步功能.为此,我构建了一个异步Web scraper.我想限制我一次打开的连接总数,以成为服务器上的好公民.我知道信号量是一个很好的解决方案,并且asyncio库内置了一个信号量类.我的问题是,当你在组合和语法yield from
中使用async
函数时,Python会抱怨.以下是我正在使用的确切语法...yield
await
import asyncio
import aiohttp
sema = asyncio.BoundedSemaphore(5)
async def get_page_text(url):
with (yield from sema):
try:
resp = await aiohttp.request('GET', url)
if resp.status == 200:
ret_val = await resp.text()
except:
raise ValueError
finally:
await resp.release()
return ret_val
Run Code Online (Sandbox Code Playgroud)
提出这个例外:
File "<ipython-input-3-9b9bdb963407>", line 14
with (yield from sema):
^
SyntaxError: 'yield from' inside async function
Run Code Online (Sandbox Code Playgroud)
我能想到的一些可能的解决方案......
@asyncio.coroutine
装饰器我是Python的异步功能的新手,所以我可能会遗漏一些明显的东西.
我有一个数据框...
>>> df = pd.DataFrame({
... 'letters' : ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],
... 'is_min' : np.zeros(9),
... 'numbers' : np.random.randn(9)
... })
is_min letters numbers
0 0 a 0.322499
1 0 a -0.196617
2 0 a -1.194251
3 0 b 1.005323
4 0 b -0.186364
5 0 b -1.886273
6 0 c 0.014960
7 0 c -0.832713
8 0 c 0.689531
Run Code Online (Sandbox Code Playgroud)
如果“数字”是“字母”列的最小值,我想将“is_min”列设置为 1。我试过这个,觉得我很接近......
>>> df.groupby('letters')['numbers'].transform('idxmin')
0 2
1 2
2 2
3 5
4 5 …
Run Code Online (Sandbox Code Playgroud) 下面是一个有点人为的例子,它解决了我最终的问题......
我想使用正则表达式将所有格名词的第一个字符大写。假设我有一个正则表达式(可能很差)匹配所有格名词。IE...
### Regex explanation ###
# 1. match a word break
# 2. match a word-like character and capture in a group
# 3. lookahead for some more characters + the substring "'s"
>>> my_re = re.compile(r"\b(\w)(?=\w+'s)")
>>> re.search(my_re, "bruce's computer")
<_sre.SRE_Match object; span=(0, 1), match='b'>
>>> re.search(my_re, "bruce's computer").group(1)
'b'
Run Code Online (Sandbox Code Playgroud)
对于此示例,它按预期工作。所以,我认为所有要做的就是在 sub 中的第一组上调用 upper 并且它应该可以工作,对吧?
>>> re.sub(my_re, r'\1'.upper(), "bruce's computer")
"bruce's computer"
Run Code Online (Sandbox Code Playgroud)
这不是预期的或显而易见的为什么它不是资本。经过一番研究,我在 re.sub 文档中发现了这一点...
返回通过替换 repl 替换 string 中模式的最左侧非重叠出现而获得的字符串。repl 可以是字符串或可调用的;如果是字符串,则处理其中的反斜杠转义。如果它是可调用的,则传递匹配对象并且必须返回要使用的替换字符串。
确实传递一个可调用的确实有效......
>>> re.sub(my_re, lambda x: x.group(1).upper(), …
Run Code Online (Sandbox Code Playgroud) 我想删除每行"Name"列的最后4个字符.这就是我尝试过的.
hof_pitching.final[, Name := substring(hof_pitching.final$Name, 0, (length(hof_pitching.final$Name) - 4))]
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.
我试图解决的问题是映射多线程庄园中的函数列表.这些函数既可以打印出来,也可以返回值.这些返回值中的每一个都将存储在列表中.这是代码......
import threading
import time
def PauseAndPrint1Seconds(num):
time.sleep(1)
print("Finished Pausing" + num)
return [1]
def PauseAndPrint2Seconds(num):
time.sleep(2)
print("Finished Pausing" + num)
return [2, 2]
def PauseAndPrint3Seconds(num):
time.sleep(3)
print("Finished Pausing" + num)
return [3, 3, 3]
def PauseAndPrint4Seconds(num):
time.sleep(4)
print("Finished Pausing" + num)
return [4, 4, 4, 4]
myfuncs = [PauseAndPrint1Seconds, PauseAndPrint2Seconds, PauseAndPrint3Seconds, PauseAndPrint4Seconds]
result = [None] * len(myfuncs)
def wrapFunc(i, num):
result[i] = myfuncs[i](num)
mythreads = [threading.Thread(target=wrapFunc, args = (i, " 12345")) for i in range(len(myfuncs))]
map(lambda x: x.start(), mythreads) …
Run Code Online (Sandbox Code Playgroud) python ×5
pandas ×2
data.table ×1
numpy ×1
performance ×1
python-3.5 ×1
python-3.6 ×1
r ×1
regex ×1
semaphore ×1
string ×1