Python Pandas:数据框中的布尔函数

时间:2019-02-17 17:55:09

标签: python pandas

我试图选择索引值以1或4结尾的数据帧df_A的行,并将它们捕获到另一个数据帧df_s1s4中。 我得到以下提示:“将布尔值函数传递给.loc或.iloc方法,该函数将检查索引字符串是否以1或4结尾。”

我尝试了以下操作,但无法正常工作。

import numpy as np

import pandas as pd

heights_A=pd.Series([176.2,158.4,167.6,156.2,161.4], index=['s1','s2','s3','s4','s5'])
weights_A=pd.Series([85.1,90.2,76.8,80.4,78.9], index=['s1','s2','s3','s4','s5'])
df_A=pd.DataFrame({'Student_height':heights_A, 'Student_weight':weights_A})
df_s1s4=df_A.loc[:,df_A.columns.str.endswith('1','4')]

print(df_s1s4)

有人可以建议我如何使用布尔函数来解决此问题吗?

2 个答案:

答案 0 :(得分:1)

您可以将布尔数组与.loc一起使用:

df_s1s4 = df_A.loc[(df_A.index.str.endswith('1') | df_A.index.str.endswith('4'))]

    Student_height  Student_weight
s1           176.2            85.1
s4           156.2            80.4

答案 1 :(得分:-1)

df_s1s4 = df_A.iloc [[如果[[0,3]中的str(i)[-1]为i,则[0,3]中为i,i]