如何在以下代码中将 plotly express 条形图的颜色更改为绿色?
import plotly.express as px
import pandas as pd
# prepare the dataframe
df = pd.DataFrame(dict(
x=[1, 2, 3],
y=[1, 3, 2]
))
# prepare the layout
title = "A Bar Chart from Plotly Express"
fig = px.bar(df,
x='x', y='y', # data from df columns
color= pd.Series('green', index=range(len(df))), # does not work
title=title,
labels={'x': 'Some X', 'y':'Some Y'})
fig.show()
Run Code Online (Sandbox Code Playgroud) 想要使用 YAML 设置带有过滤器的记录器。
YAML配置文件config.yaml如下:
version: 1
formatters:
simple:
format: "%(asctime)s %(name)s: %(message)s"
extended:
format: "%(asctime)s %(name)s %(levelname)s: %(message)s"
filters:
noConsoleFilter:
class: noConsoleFilter
handlers:
console:
class: logging.StreamHandler
level: INFO
formatter: simple
filters: [noConsoleFilter]
file_handler:
class: logging.FileHandler
level: INFO
filename: test.log
formatter: extended
root:
handlers: [console, file_handler]
propagate: true
Run Code Online (Sandbox Code Playgroud)
...主程序如下main.py:
import logging.config
import yaml
class noConsoleFilter(logging.Filter):
def filter(self, record):
print("filtering!")
return not (record.levelname == 'INFO') & ('no-console' in record.msg)
with open('config.yaml', 'r') as f:
log_cfg = yaml.safe_load(f.read())
logging.config.dictConfig(log_cfg) …Run Code Online (Sandbox Code Playgroud) 下面是一个收集 URL 长度的简单程序。
import aiohttp
import asyncio
from time import perf_counter
URLS = ['http://www.cnn.com', 'http://www.huffpost.com', 'http://europe.wsj.com',
'http://www.bbc.co.uk', 'http://failfailfail.com']
async def async_load_url(url, session):
try:
async with session.get(url) as resp:
content = await resp.read()
print(f"{url!r} is {len(content)} bytes")
except IOError:
print(f"failed to load {url}")
async def main():
async with aiohttp.ClientSession() as session:
tasks = [async_load_url(url, session) for url in URLS]
await asyncio.wait(tasks)
if __name__ == "__main__":
start = perf_counter()
asyncio.run(main())
elapsed = perf_counter() - start
print(f"\nTook {elapsed} seconds")
Run Code Online (Sandbox Code Playgroud)
为什么以下代码在 python 3.9 中失败并出现运行时错误并忽略异常?如何修复它? …
我正在尝试使用收集的异步任务的 tqdm 进度条。
希望在完成任务后逐步更新进度条。试过代码:
import asyncio
import tqdm
import random
async def factorial(name, number):
f = 1
for i in range(2, number+1):
await asyncio.sleep(random.random())
f *= i
print(f"Task {name}: factorial {number} = {f}")
async def tq(flen):
for _ in tqdm.tqdm(range(flen)):
await asyncio.sleep(0.1)
async def main():
# Schedule the three concurrently
flist = [factorial("A", 2),
factorial("B", 3),
factorial("C", 4)]
await asyncio.gather(*flist, tq(len(flist)))
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
...但这只是完成了 tqdm 条,然后处理阶乘。
有没有办法在每个 asyncio 任务完成后让进度条移动?
有两个数据框:
df1 =
Col Date Days
0 A 20180830 30
1 A 20180927 58
2 A 20181025 86
3 B 20180830 30
4 B 20180927 58
5 B 20181025 86
6 C 20180802 2
7 C 20180809 9
8 C 20180816 16
9 C 20180823 23
Run Code Online (Sandbox Code Playgroud)
df2 =
Col Lot Pct
13 A 4000 16.19
184 B 600 7.51
206 C 250 5.00
...
Run Code Online (Sandbox Code Playgroud)
如何制作单个数据框:
df =
Col Date Days Lot Pct
0 A 20180830 30 4000 16.19
1 A …Run Code Online (Sandbox Code Playgroud) 如何将 acontinue放入具有函数的列表理解中?
以下示例代码...
import pandas as pd
l = list(pd.Series([1,3,5,0,6,8]))
def inverse(x):
if x == 0:
print('not ok')
continue
else:
print('ok')
return 1/x
[inverse(x) for x in l]
Run Code Online (Sandbox Code Playgroud)
...给出:
语法错误:“继续”在循环中不正确
预期输出是:
ok
ok
ok
not ok
ok
ok
[1.0, 0.3333333333333333, 0.2, 0.16666666666666666, 0.125]
Run Code Online (Sandbox Code Playgroud) 在下面的代码中:
import pandas as pd
import numpy as np
import random
sz = 50
df = pd.DataFrame({'Group': pd.Series(random.choice(['A', 'B']) for _ in range(sz)),
'Key': pd.Series(np.random.randint(2, high=5, size=sz))})
dictforA = {2: 0.1, 3: 0.8, 4: 0.2}
dictforB = {3: 0.9}
Run Code Online (Sandbox Code Playgroud)
...想要分配一个新列Value,该列基于其各自的字典。缺少的值为NaN。
代码:
df.assign(Value=df.groupby('Group').apply(lambda x: np.where(x.index == 'A', dictforA[x.Key], dictforB[x.Key])))
给
TypeError: 'Series' objects are mutable, thus they cannot be hashed
我要去哪里错了?