python - 在python中获取与pandas中的行相关的值

标签 python pandas

我有一个 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/

相关文章:

python - 计算数据框中一行的百分比值

python - 从二维数组python创建直方图

python - 如何使用python在同一个字典中调用方法

python - 对于两个列表 l1 和 l2,如何在 python 中有效地检查所有 e1 ∈ l1, ∃p(e1,e2) 其中 e2 是 l2 中的某个元素?

pandas - 属性错误: 'StructType' object has no attribute 'encode'

python - Pandas 中的间隔数据类型 - 查找中点、左侧、中心等

python - 使用 pandas 方法链接过滤每组中任何一个满足条件的行

python - 一个数据帧与另一个数据帧的相关矩阵

python - 在Python中使用正则表达式获取字符串的一部分

python - 访问 job.get_output ('body' 中的流)