选择python pandas数据框的后两列中包含相同文本的行

时间:2019-12-26 19:04:54

标签: python pandas loops if-statement

我有一个看起来在下面的数据框

import pandas as pd

k={'ID':[1,2,3,4,5,6],'m1':['jj','nn','jj','nn','nn','nn'],
   'm2':['jj','nn','nn','jj','jj','jj'],
   'm3':['jj','','nn','jj','jj','jj'],
   'm4':['nn','','nn','jj','jj','jj'],
   'm5':['nn','','','jj','jj','nn'],
   'm6':['','','','jj','jj','nn']}

df=pd.DataFrame(data=k)

ID  m1  m2  m3  m4  m5  m6
1   jj  jj  jj  nn  nn  
2   nn  nn              
3   jj  nn  nn  nn      
4   nn  jj  jj  jj  jj  jj
5   nn  jj  jj  jj  jj  jj
6   nn  jj  jj  jj  nn  nn

我们必须选择在最后两列中包含“ nn”的ID ,但每行的最后一列(ID)不同

我想要的结果如下

ID  last1   last2   last two columns are nn
1   nn       nn         yes
2   nn       nn         yes
3   nn       nn         yes
6   nn       nn         yes 

2 个答案:

答案 0 :(得分:3)

IIUC meltgroupby,然后选择tail 2

s=df.melt('ID').loc[lambda x : x.value!=''].groupby('ID').tail(2)
s['variable']=s.groupby('ID').cumcount()
s=s.pivot(*s.columns)
s
Out[86]: 
variable   0   1
ID              
1         nn  nn
2         nn  nn
3         nn  nn
4         jj  jj
5         jj  jj
6         nn  nn

像上面一样获得df之后,就可以拿起它

答案 1 :(得分:1)

尝试一下

function uploadFiles(PIRid) {
var fileInput = $('#incidentFiles');

var fileCount = fileInput[0].files.length;
for (i = 0; i < fileCount; i++){
    var Obj = new Object();
    Obj.Name = fileInput[0].files[i].name;
    var reader = new FileReader();
    Obj.File = reader.readAsBinaryString(fileInput[0].files[i]);
    Obj.PIRid = PIRid;
    Obj.RemoteID = RemoteID;
    var data = JSON.stringify(Obj);
    $.ajax({
        type: "POST",
        url: BaseHref + "/api/PIRfiles/",
        data: data,
        contentType: "application/json; charset=UTF-8",
        success: function (response) {
            $('#SaveSuccess').modal();
        },
        error: function (e) {
            $('#SaveFailure').modal();
        }
    });
}

结果:

public class ApiPIRfile
{
    public string Name;
    public byte[] File;
    public string PIRid;
    public string RemoteID;
}