我有一个 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
中项目的标题
和详细信息
。因此,我的输出如下所示。
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
选择行然后将连接的列转换为列表
:
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']
关于python - 在python中获取与pandas中的行相关的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48127893/