python - 如何在 fstrings 中使用 .loc?
问题描述
我有一个这样的数据框:
import pandas as pd
df = pd.DataFrame({'col1': ['abc', 'def', 'tre'],
'col2': ['foo', 'bar', 'stuff']})
col1 col2
0 abc foo
1 def bar
2 tre stuff
和这样的字典:
d = {'col1': [0, 2], 'col2': [1]}
字典包含要从数据框中提取的列名和值的索引以生成如下字符串:
abc (0, col1)
因此,每个字符串都以元素本身开头,并在括号中显示索引和列名。
我尝试了以下列表理解:
l = [f"{df.loc[{indi}, {ci}]} ({indi}, {ci})"
for ci, vali in d.items()
for indi in vali]
产生
[' col1\n0 abc (0, col1)',
' col1\n2 tre (2, col1)',
' col2\n1 bar (1, col2)']
所以,几乎没问题,只是col1\n0
需要避免的部分。
如果我尝试
f"{df.loc[0, 'col1']} is great"
我明白了
'abc is great'
然而,根据需要,与
x = 0
f"{df.loc[{x}, 'col1']} is great"
我明白了
'0 abc\nName: col1, dtype: object is great'
这怎么可能解决?
解决方案
import pandas as pd
df = pd.DataFrame({'col1': ['abc', 'def', 'tre'],
'col2': ['foo', 'bar', 'stuff']})
d = {'col1': [0, 2], 'col2': [1]}
x = 0
[f"{df.loc[x, 'col1']} is great"
for ci, vali in d.items()
for indi in vali]
这给了你:
['abc is great', 'abc is great', 'abc is great']
这是你要找的吗?
您也可以通过 x 范围进行循环
[f"{df.loc[i, 'col1']} is great"
for ci, vali in d.items()
for indi in vali
for i in range(2)]
#output
['abc is great',
'def is great',
'abc is great',
'def is great',
'abc is great',
'def is great']
推荐阅读
- javascript - Google.script.run 功能在 firefox、safari 中失败
- dataframe - 2个数据框之间的匹配行
- r - 在 r 中提取不同值的最快方法
- angular - Angular - 如何将数据从一个组件传递到另一个
- python - 为什么ipynb文件在不同的电脑上打开的大小不同?
- c++ - 为什么这个 c++ 程序不能正常运行?
- ios - 当它们嵌入导航控制器时,标签栏无法识别视图控制器
- python - Impyla - 用户没有执行“SELECT”的权限
- r - VIF 无拦截:vifs 可能不明智
- python - Errno 13 权限被拒绝:'tmp\\csv.gz