从其他数据框中选择具有特定条件的行

时间:2019-04-17 09:03:31

标签: python pandas select rows

我有一个数据框df,其中有一列:

colors
red
blue
green
black
pink

另一个具有许多列(约300列)的数据帧df1

colorName col1 col2 ... colN
pink 1 0 1 ... 0
white 0 1 1 ... 1
blue 1 0 0 ... 0
yellow 0 0 0 ... 0

我需要返回df中存在的df1.colorName行,并且在任何列(col1 ... colN)中至少具有值1

因此,从上面来看;输出应为:

blue
pink

我从这里开始,但是我确定它需要其他条件(检查任何列(col1 ... colN)的值至少为1)

newDF = df[df.colors.isin(df1.colorName) && ]

如果我错了,请纠正我,我们将不胜感激。

1 个答案:

答案 0 :(得分:2)

boolean indexingDataFrame.iloc的选择列一起使用-所有不带DataFrame.any的列均不包含第一列,True每行至少DataFrame.loc列{{ 1}},然后将其传递给Series.isin进行过滤:

colorName

详细信息

c = df1.loc[df1.iloc[:, 1:].any(axis=1), 'colorName']
#alternative
#c = df1.loc[df1.drop('colorName', axis=1).any(axis=1), 'colorName']
newDF = df[df. colors.isin(c)]
print (newDF)
  colors
1   blue
4   pink
相关问题