获取python中与行相关的值

2024-05-16 20:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧如下。你知道吗

            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]

我想得到titledetails中的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是错误的。请告诉我怎么修?你知道吗


Tags: dfheretitlerecipedetailscakewafflebeans
2条回答

您可以首先按^{}选择行,然后将连接的列转换为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']

在代码中使用^{},因此默认值的顺序是:

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']

可以使用list comprehension创建所需的列表:

mydetails = ["".join(df.values[n])    for n in mylist]
print(mydetails)

输出:

['waffle recipewaffle recipe comes here', 'chocolate recipechocolate recipe comes here', 'cake recipecake recipe comes here']

df.values是所有行作为列表的列表。"".join用于连接每行的两个列值。你知道吗

要在两个条目之间添加句点和空格,可以使用". ".join()

或者,可以根据需要添加逗号或分号。你知道吗

相关问题 更多 >