Python 如何在fstring中使用.loc?
我有这样一个数据帧:Python 如何在fstring中使用.loc?,python,string,pandas,indexing,f-string,Python,String,Pandas,Indexing,F String,我有这样一个数据帧: 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) 还有一本这样的
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)
还有一本这样的字典:
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)
字典包含要从数据帧中提取的列名和值索引,以生成如下字符串:
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"
我明白了
然而,正如所希望的那样
x = 0
f"{df.loc[{x}, 'col1']} 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范围
您看到的是
loc
acessor返回的pd.Series
对象的字符串表示形式和难看的换行符
您应该使用返回标量,并注意这里不需要为索引标签嵌套{}
:
L = [f'{df.at[indi, ci]} ({indi}, {ci})' \
for ci, vali in d.items() \
for indi in vali]
print(L)
['abc (0, col1)', 'tre (2, col1)', 'bar (1, col2)']
很好,只要删除
{}
就可以解决问题,即使使用了.loc
,但是.at
可能会更快。谢谢,但您不使用字典d
。但是@jpp的回答解决了这个问题。比预期的容易。