我有一个 pandas 数据框,如下所示。
title details
0 cake recipe cake recipe comes here
1 bread recipe bread recipe comes here
2 chocolate recipe chocolate recipe comes here
3 biscuit recipe biscuit recipe comes here
4 beans recipe beans recipe comes here
5 waffle recipe waffle recipe comes here
6 pudding recipe pudding recipe comes here
我还有一个列表如下。
mylist = [5, 2, 0]
我想获取 mylist 中项目的 title 和 details。因此,我的输出如下所示。
mydetails = ['waffle recipe. waffle recipe comes here', 'chocolate recipe chocolate recipe comes here', 'cake recipe cake recipe comes here']
我目前的代码如下。
mydetails = []
v = df.loc[df.index.isin(mylist)]
item_details= v.title + '. ' + v.details
for val in item_details:
mydetails.append(val)
但是,我得到的v 是错误的。请告诉我如何解决这个问题?
请您参考如下方法:
您可以先通过 loc 选择行然后将连接的列转换为 list:
df = df.loc[mylist]
mydetails = (df.title + '. ' + df.details).values.tolist()
print (mydetails )
['waffle recipe. waffle recipe comes here',
'chocolate recipe. chocolate recipe comes here',
'cake recipe. cake recipe comes here']
在你的代码中使用了boolean indexing ,所以值的顺序是默认的:
v = df.loc[df.index.isin(mylist)]
print (v)
title details
0 cake recipe cake recipe comes here
2 chocolate recipe chocolate recipe comes here
5 waffle recipe waffle recipe comes here
为了正确的输出删除isin:
mydetails = []
v = df.loc[mylist]
item_details= v.title + '. ' + v.details
for val in item_details:
mydetails.append(val)
print (mydetails)
['waffle recipe. waffle recipe comes here',
'chocolate recipe. chocolate recipe comes here',
'cake recipe. cake recipe comes here']
