我需要使用 python 日志模块来记录熊猫数据帧。我需要同等缩进的整个数据框(所有行)。
以下是简单的所需输出:
Test Dataframe Output Below:
col1 col2
0 1 3
1 2 4
Run Code Online (Sandbox Code Playgroud)
但是,我得到以下输出,其中缩进仅应用于数据帧的第一行:
Test Dataframe Output Below:
col1 col2
0 1 3
1 2 4
Run Code Online (Sandbox Code Playgroud)
我正在运行的示例代码是:
import pandas as pd
import logging
# sample dataframe
test_df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
# logging set up
logging.basicConfig(level=logging.INFO)
logging.getLogger().handlers.clear()
c_handler = logging.StreamHandler()
c_handler.setFormatter(logging.Formatter('%(message)s'))
logging.getLogger().addHandler(c_handler)
# log the pandas dataframe to console
logging.info(f'\tTest Dataframe Output Below:')
logging.info(f'\n\t\t{test_df}')
logging.info(f'{test_df}')
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!
我想打印一个非常非常接近 1 的浮点数,将其截断到小数点后两位而不进行四舍五入,最好使用尽可能少的代码。
a = 0.99999999999
print(f'{a:0.2f}')
Run Code Online (Sandbox Code Playgroud)
Expected: 0.99
Actual: 1.00
Run Code Online (Sandbox Code Playgroud) 我需要通过他们的 API 将数据推送到网站,并且我正在尝试找到一种使用 F 字符串传递数据列表中的变量的方法,但找不到方法。
到目前为止,这是我尝试过的:
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1)
#trying to pass *tomorrow* value with f-string below
data = f'[{"date": "{tomorrow}", "price": {"amount": 15100}}]'
response = requests.put('https://api.platform.io/calendar/28528204', headers=headers, data=data)
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这个目标?
我想在我的 f 字符串中设置精度,但我不希望小数部分尾随零。
i = 1002
print(f'{i/1000:.2f}') # 1.00 but this must be 1
i = 1009
print(f'{i/1000:.2f}') # 1.01, this is correct
Run Code Online (Sandbox Code Playgroud)
第一个print必须是1,我的预期行为在第二个中print可见1.01。
我尝试过:g,但它对第一个有效print,但对第二个失败。
i = 1000
print(f'{i/1000:.2g}') # 1, this is correct but
i = 1009
print(f'{i/1000:.2g}') # 1, but this must be 1.01
Run Code Online (Sandbox Code Playgroud)
我尝试过的一种方法是,f'{i/1000:.2f}'.strip('.0')但我想知道是否有更好的方法。
编辑 :
在我的实际代码中,如果i是100000,那么分母也将是 100000(按 顺序的最小数字i),换句话说,我的代码中的分母将始终是这样的,即 i// 分母将始终产生一个数字。
我有一个pd系列,
s = pd.Series([1, 2, 3, np.nan])
Run Code Online (Sandbox Code Playgroud)
当我做,
s.map('this is a string {}'.format)
[out]
0 this is a string 1.0
1 this is a string 2.0
2 this is a string 3.0
3 this is a string nan
Run Code Online (Sandbox Code Playgroud)
如何使用格式化字符串获得相同的结果?
s.map(f'this is a string {?}') ?
Run Code Online (Sandbox Code Playgroud) 我正在使用 python 3.7 编写一个应用程序,并且只想在其中使用f 字符串。
我正在使用 python 日志记录模块来正确记录我的应用程序,我想使用特定的格式,但文档(和网络)仅举例说明如何使用 %-strings 更改格式。我想知道是否有使用 f-strings 设置记录器格式的选项
LOG_FORAMT = ('%(levelname)s -10s %(asctime)s -10s %(message)s') # Known example
f-LOG_FORMAT = (f'{logger.levelname} -10s') # Something like that?
Run Code Online (Sandbox Code Playgroud) 从python 3.6开始,将值格式化为字符串的最短,最高效的方法是PEP 498 f字符串(例如f'Hello {name}')。
在现有代码库中将旧的格式设置类型('Hello %s' % name,'Hello {}'.format(name))转换为新的格式设置似乎是可以自动化的任务,但是我找不到执行此操作的任何工具。是否有工具可以将使用旧字符串格式的文字自动转换为f字符串?
当字符串转换为 f 字符串时,以下代码会导致无效的格式说明符。我无法确定问题出在哪里,因为我的报价看起来没问题。
expected_document = f'{"name":"tenders","value":"chicken","key":"{key}"}'
Run Code Online (Sandbox Code Playgroud)
原因:
> expected_document = f'{"name":"tenders","value":"chicken","key":"{key}"}'
E ValueError: Invalid format specifier
Run Code Online (Sandbox Code Playgroud)
同时删除f:
expected_document = '{"name":"tenders","value":"chicken","key":"{key}"}'
Run Code Online (Sandbox Code Playgroud)
工作正常。
Python 中是否有 (eg) 的简写print(f'type(var) = {type(var)}'),而不必在文本和{.}?
简短的回答可能是“不”,但我不得不问!
例如,在 SAS 中,可以使用&=将宏变量及其值输出到日志...
%let macrovar = foobar;
%put &=macrovar;
Run Code Online (Sandbox Code Playgroud)
在日志中返回: MACROVAR = foobar
这是我的第一个问题,我发现很难找到答案,所以如果有人问并回答了,我深表歉意。
我正在使用 timeit 对项目的一些代码进行基准测试(使用免费的 replit,因此需要 1024MB 内存):
\ncode = \'{"type":"body","layers":[\'\n\nfor x, row in enumerate(pixels):\n for y, pixel in enumerate(row):\n if pixel != (0, 0, 0, 0):\n code += f\'\'\'{{"offsetX":{-start + x * gap},"offsetY":{start - y * gap},"rot":45,"size":{size},"sides":4,"outerSides":0,"outerSize":0,"team":"{\'#%02x%02x%02x\' % (pixel[:3])}","hideBorder":1}},\'\'\'\n \ncode += \'],"sides":1,"name":"Image"}}\nRun Code Online (Sandbox Code Playgroud)\n该循环针对给定图像内的每个像素运行(当然效率不高,但我还没有实现任何减少循环时间的方法),因此我可以在循环中获得的任何优化都是值得的。
\n我记得只要你组合 3 个以上的字符串\xe2\x80\x94,f 字符串就比字符串连接更快,如图所示,我组合了超过3个字符串\xe2\x80\x94,所以我决定将循环内的 += 替换为 f 字符串并查看改进。
\ncode = \'{"type":"body","layers":[\'\n\nfor x, row in enumerate(pixels):\n for y, pixel in enumerate(row):\n if pixel != (0, 0, 0, 0):\n code = f\'\'\'{code}{{"offsetX":{-start + x …Run Code Online (Sandbox Code Playgroud) f-string ×10
python ×9
python-3.x ×4
format ×2
pandas ×2
string ×2
decimal ×1
formatting ×1
json ×1
list ×1
logging ×1
loops ×1
python-3.6 ×1
python-3.7 ×1
sas ×1
series ×1