标签: f-string

python 3.6+记录器记录pandas数据帧 - 如何缩进整个数据帧?

我需要使用 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)

任何帮助将不胜感激!

python logging python-3.x pandas f-string

7
推荐指数
1
解决办法
5802
查看次数

截断 f 字符串浮点数而不进行舍入

我想打印一个非常非常接近 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)

python floating-point decimal f-string

7
推荐指数
1
解决办法
5772
查看次数

在 json 数据列表中使用 python f-string

我需要通过他们的 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)

我怎样才能实现这个目标?

python json list f-string

7
推荐指数
1
解决办法
2万
查看次数

如何使用 f 字符串跳过小数中的尾随零

我想在我的 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')但我想知道是否有更好的方法。

编辑 :

在我的实际代码中,如果i100000,那么分母也将是 100000(按 顺序的最小数字i),换句话说,我的代码中的分母将始终是这样的,即 i// 分母将始终产生一个数字。

python format python-3.x f-string

7
推荐指数
1
解决办法
4120
查看次数

python f'string 在 pd.Series.map 函数中不起作用

我有一个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 format series pandas f-string

6
推荐指数
1
解决办法
1264
查看次数

如何使用 f-string 样式设置 python.logging 格式

我正在使用 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.x python-3.6 f-string python-3.7 python-logging

6
推荐指数
1
解决办法
3872
查看次数

有没有一种工具可以将字符串格式类型自动转换为f字符串?

从python 3.6开始,将值格式化为字符串的最短,最高效的方法是PEP 498 f字符串(例如f'Hello {name}')。

在现有代码库中将旧的格式设置类型('Hello %s' % name'Hello {}'.format(name))转换为新的格式设置似乎是可以自动化的任务,但是我找不到执行此操作的任何工具。是否有工具可以将使用旧字符串格式的文字自动转换为f字符串?

python string formatting f-string

6
推荐指数
2
解决办法
133
查看次数

如何在字典字符串周围使用 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 python-3.x f-string

6
推荐指数
2
解决办法
6487
查看次数

Python - [eg] 是否有简写:print(f'type(var) = {type(var)}')

Python 中是否有 (eg) 的简写print(f'type(var) = {type(var)}'),而不必在文本和{.}?

简短的回答可能是“不”,但我不得不问!

例如,在 SAS 中,可以使用&=将宏变量及其值输出到日志...

%let macrovar = foobar;  
%put &=macrovar;
Run Code Online (Sandbox Code Playgroud)

在日志中返回: MACROVAR = foobar

这是我的第一个问题,我发现很难找到答案,所以如果有人问并回答了,我深表歉意。

python sas string-formatting f-string

6
推荐指数
1
解决办法
90
查看次数

在循环内重复添加字符串时,为什么 f 字符串比字符串连接慢?

我正在使用 timeit 对项目的一些代码进行基准测试(使用免费的 replit,因此需要 1024MB 内存):

\n
code = \'{"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"}}\n
Run Code Online (Sandbox Code Playgroud)\n

该循环针对给定图像内的每个像素运行(当然效率不高,但我还没有实现任何减少循环时间的方法),因此我可以在循环中获得的任何优化都是值得的。

\n

我记得只要你组合 3 个以上的字符串\xe2\x80\x94,f 字符串就比字符串连接更快,如图所示,我组合了超过3个字符串\xe2\x80\x94,所以我决定将循环内的 += 替换为 f 字符串并查看改进。

\n
code = \'{"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)

python string loops concatenation f-string

6
推荐指数
1
解决办法
576
查看次数