繁体   English   中英

如何选择行中至少一个元素中包含特定值的行?

[英]How to select the rows that contain a specific value in at least one of the elements in a row?

我有一个DataFrame DF和一个列表,例如List1 List1是从DF创建的,它具有DF存在的元素,但没有重复。 我需要执行以下操作:
1.从List1选择包含特定元素的DF行(例如,迭代List1所有元素)
2.将它们从0重新索引到任意行数,因为选择的行可能具有不连续的索引。

样本输入:

List1=['Apple','Orange','Banana','Pineapple','Pear','Tomato','Potato']
Sample DF
  EQ1      EQ2      EQ3
0 Apple    Orange   NaN
1 Banana   Potato   NaN
2 Pear     Tomato   Pineapple
3 Apple    Tomato   Pear
4 Tomato   Potato   Banana

现在,如果我要访问包含Apple的行,它们将为0和3。但是我希望将它们重命名为0和1(重新索引)。 搜索Apple之后,应采用List1的下一个元素,并执行类似的步骤。 此后,我还有其他操作要执行,因此需要在整个List1循环整个过程。 我希望我已经很好地解释了,这是我的相同代码,它无法正常工作:

for eq in List1:
    MCS=DF.loc[MCS_Simp_green[:] ==eq] #Indentation was missing
    MCS= MCS.reset_index(drop=True)
    <Remaining operations>

我认为您需要isinany

List1=['Apple','Orange','Banana','Pineapple','Pear','Tomato','Potato']

for eq in List1:
    #print df.isin([eq]).any(1)
    #print df[df.isin([eq]).any(1)]
    df1 = df[df.isin([eq]).any(1)].reset_index(drop=True)  
    print df1

     EQ1     EQ2   EQ3
0  Apple  Orange   NaN
1  Apple  Tomato  Pear
     EQ1     EQ2  EQ3
0  Apple  Orange  NaN
      EQ1     EQ2     EQ3
0  Banana  Potato     NaN
1  Tomato  Potato  Banana
    EQ1     EQ2        EQ3
0  Pear  Tomato  Pineapple
     EQ1     EQ2        EQ3
0   Pear  Tomato  Pineapple
1  Apple  Tomato       Pear
      EQ1     EQ2        EQ3
0    Pear  Tomato  Pineapple
1   Apple  Tomato       Pear
2  Tomato  Potato     Banana
      EQ1     EQ2     EQ3
0  Banana  Potato     NaN
1  Tomato  Potato  Banana

要存储值,可以使用dict理解:

dfs = {eq: df[df.isin([eq]).any(1)].reset_index(drop=True) for eq in List1}

print dfs['Apple']
     EQ1     EQ2   EQ3
0  Apple  Orange   NaN
1  Apple  Tomato  Pear

print dfs['Orange']
     EQ1     EQ2  EQ3
0  Apple  Orange  NaN

您可以标识list的项目并收集生成的新DataFrame如下所示:

data_frames = {}
for l in List1:
    data_frames[l] = df[df.isin([l]).any(1)].reset_index(drop=True)
    print(l, data_frames[l].index.tolist())

要得到:

Apple [0, 1]
Orange [0]
Banana [0, 1]
Pineapple [0]
Pear [0, 1]
Tomato [0, 1, 2]
Potato [0, 1]

新的DataFrame对象包含在dictionary data_frames

data_frames['Apple']

     EQ1     EQ2   EQ3
0  Apple  Orange   NaN
1  Apple  Tomato  Pear

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM