该文档指定collections.Counter.most_common(),
相等计数的元素是任意排序的。
我对一种简洁的方法感兴趣,该方法首先按频率/值降序(默认)排序,然后按键升序排序。(键只是。中每个元组的第0个元素.most_common()。)
例:
from collections import Counter
arr1 = [1, 1, 1, 2, 2, 3, 3, 3, 5]
arr2 = [3, 3, 3, 1, 1, 1, 2, 2, 5] # Same values, different order
print(Counter(arr1).most_common())
print(Counter(arr2).most_common())
# [(1, 3), (3, 3), (2, 2), (5, 1)]
# [(3, 3), (1, 3), (2, 2), (5, 1)]
Run Code Online (Sandbox Code Playgroud)
所需的结果(对于arr2和arr2):
[(1, 3), (3, 3), (2, 2), (5, 1)]
Run Code Online (Sandbox Code Playgroud) 我有以下配对值列表:
a = [['A', 'B'], ['A', 'C'], ['D', 'D'], ['C', 'D']]
Run Code Online (Sandbox Code Playgroud)
此列表可以包含一个或多个由同一项组成的卓越对:
['D', 'D']
我想将这些对移到列表的末尾以获得:
a = [['A', 'B'], ['A', 'C'], ['C', 'D'], ['D', 'D']]
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚,但我相信我并不太远:
a.append(a.pop(x) for x in range(len(a)) if a[x][0] == a[x][1])
Run Code Online (Sandbox Code Playgroud) 我想根据另一个键的条件(例如Gender == 'male')来总结此字典列表中所有人的年龄:
list_of_dicts= [
{"Name": "Ethan", "Gender": "male", "Age": 11},
{"Name": "Nathan", "Gender": "male", "Age": 6},
{"Name": "Sophie", "Gender": "female", "Age": 14},
{"Name": "Patrick", "Gender": "male", "Age": 11}
]
Run Code Online (Sandbox Code Playgroud)
下面的代码完成了它,但我想知道是否有更Pythonic/紧凑的方法来做到这一点?也许类似于字典列表的 SQL 查询?
total_male_age = 0
for dict in list_of_dicts:
if dict.get("Gender") == "male":
total_male_age = total_male_age + dict.get("Age")
#total_male_age = 28
Run Code Online (Sandbox Code Playgroud) 我正在使用重要的特征选择来实现管道,然后使用相同的特征来训练我的随机森林分类器。以下是我的代码。
m = ExtraTreesClassifier(n_estimators = 10)
m.fit(train_cv_x,train_cv_y)
sel = SelectFromModel(m, prefit=True)
X_new = sel.transform(train_cv_x)
clf = RandomForestClassifier(5000)
model = Pipeline([('m', m),('sel', sel),('X_new', X_new),('clf', clf),])
params = {'clf__max_features': ['auto', 'sqrt', 'log2']}
gs = GridSearchCV(model, params)
gs.fit(train_cv_x,train_cv_y)
Run Code Online (Sandbox Code Playgroud)
因此,X_new可通过选择新的功能SelectFromModel和sel.transform。然后,我想使用所选的新功能来训练我的RF。
我收到以下错误:
所有中间步骤都应该是转换器,并实现拟合和转换,ExtraTreesClassifier ...
我想把文件中的单词读成这样的集合:
# Text file
bill
beep-boop
wow
apostrophe'
Run Code Online (Sandbox Code Playgroud)
然后当我打印
>>> print(mySet)
{'bill', 'beep', 'boop', 'wow', 'apostrophe'}
Run Code Online (Sandbox Code Playgroud)
所以我也不想要任何前导或结尾的撇号,但是如何在split()函数中使用多个分隔符呢?我只有这个:
mySet = set((stdin.read().split()))
Run Code Online (Sandbox Code Playgroud) 我有一个 10k 行的 csv,我想以 1k 行的块写入 s3。
from io import StringIO
import pandas as pd
csv_buffer = StringIO()
df.to_csv(csv_buffer, chunksize=1000)
s3_resource = boto3.resource('s3')
s3_resource.Object(bucket, 'df.csv').put(Body=csv_buffer.getvalue())
Run Code Online (Sandbox Code Playgroud)
这给了我要写入 s3 的字符串缓冲区中的前 1k 行,但似乎 csv 缓冲区不是我可以循环的迭代器。
有谁知道如何实现这一目标?
我已经从源代码安装并编译了Redis,并试图连接到Amazon ElastiCache(Redis)集群。
我可以毫无问题地连接到默认本地主机,但是尝试连接到AWS终端节点会导致无限的挂断。
使用默认值:
$ redis-server /etc/redis.conf # daemonized, uses localhost
$ redis-cli ping
PONG
$ sudo service redis_6379 status
Redis is running (12919)
$ redis-cli shutdown # or sudo service redis_6379 stop
Run Code Online (Sandbox Code Playgroud)
现在,这是尝试连接到终端节点的尝试,它是有关该主题的AWS文档的副本:
redis-cli -c -h my_example_endpoint_name.eaogs8.ng.0001.use1.cache.amazonaws.com -p 6379 ping
Run Code Online (Sandbox Code Playgroud)
这会无限地挂起,而不会发出任何东西到stderr / stdout。
(请注意,这是一个示例端点名称;我已验证自己正在使用AWS控制台上列出的主要端点。)
我怀疑这可能与AWS端群集的安全组设置有关,但不确定具体可以/应该修改什么。我对可能阻止连接的建议表示赞赏,并可以根据需要提供有关群集本身的信息。
我正在尝试从Pandas DataFrame中获取具有连续日期的数据块。我的df样子如下。
DateAnalyzed Val
1 2018-03-18 0.470253
2 2018-03-19 0.470253
3 2018-03-20 0.470253
4 2018-09-25 0.467729
5 2018-09-26 0.467729
6 2018-09-27 0.467729
Run Code Online (Sandbox Code Playgroud)
在此df,我想获取前3行,进行一些处理,然后获取后3行,并对此进行处理。
我通过应用以下代码计算了1滞后的差异。
df['Delta']=(df['DateAnalyzed'] - df['DateAnalyzed'].shift(1))
Run Code Online (Sandbox Code Playgroud)
但是在那之后,我无法弄清楚如何在不进行迭代的情况下获取连续行的组。
我在使用 Spyder 的 Python 中遇到一个非常简单的错误:
\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt \n\nds=pd.read_csv(".\\verikumesi\\NBA_player_of_the_week.csv")\nRun Code Online (Sandbox Code Playgroud)\n\n当我运行上面的代码时,出现错误:
\n\n\n\n\n文件“C:/Users/Acer/Desktop/MASA\xc3\x9cST\xc3\x9c/github/deneme.py”,第 12 行\n ds=pd.read_csv(“.\\verikumesi\\NBA_player_of_the_week.csv”) \n ^ SyntaxError: (unicode error) \'unicodeescape\' 编解码器无法解码位置 12-13 中的字节:格式错误 \\N 字符\n 转义
\n
我该如何修复它?
\n我见过asyncio.gather 与 asyncio.wait,但我不确定这是否解决了这个特定问题。我想要做的是将asyncio.gather()协程包装在中asyncio.wait_for(),并带有一个timeout参数。我还需要满足以下条件:
return_exceptions=True(from asyncio.gather()) - 而不是将异常传播到等待的任务gather(),我想在结果中包含异常实例asyncio.gather()结果顺序与输入顺序相同的属性。(否则,将输出映射回输入。)。 asyncio.wait_for()没有达到这个标准,我不确定实现它的理想方式。超时是针对整个 可等待asyncio.gather()列表的——如果它们在超时中被捕获或返回异常,那么这两种情况中的任何一种都应该在结果列表中放置一个异常实例。
考虑这个设置:
>>> import asyncio
>>> import random
>>> from time import perf_counter
>>> from typing import Iterable
>>> from pprint import pprint
>>>
>>> async def coro(i, threshold=0.4):
... await asyncio.sleep(i)
... if i > threshold:
... # For illustration's sake - some coroutines may raise,
... # and we want …Run Code Online (Sandbox Code Playgroud) python ×9
pandas ×3
list ×2
python-3.x ×2
amazon-s3 ×1
collections ×1
concurrency ×1
datetime ×1
dictionary ×1
io ×1
json ×1
redis ×1
regex ×1
scikit-learn ×1
set ×1
string ×1