我有一个这样的数据框:import pandas as pddf = pd.DataFrame({'col1': ['abc', 'def', 'tre'], 'col2': ['foo', 'bar', 'stuff']}) col1 col20 abc foo1 def bar2 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 = 0f"{df.loc[{x}, 'col1']} is great"我得到'0 abc\nName: col1, dtype: object is great'这怎么能解决?
2 回答
翻阅古今
TA贡献1780条经验 获得超5个赞
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']
添加回答
举报
0/150
提交
取消