Pandas DF列数据拆分

时间:2019-06-10 17:14:53

标签: python pandas

我有一个Pandas DataFrame(如下所示)

Room_ID        Chamber_ID        Floor_Name
-----------  ------------     ------------------------ 
111,222                 9 
111                     9 
None                    1 
111,222,333             1 

还有一个功能

def GetFloorName(Room_ID, Chamber_ID):
   THis Will Return the Floor_Name 

DF中的数据必须像第一行一样逐行推入功能

the Data is 111,222 in Room_ID and 9 in Chamber_id```

因此,函数调用应类似于

    GetFloorName(111,9) which will return a Value (For Eg: X)
    GetFloorName(222,9) which will return a Value (For Eg: Y)

现在,这两个值都需要在Floor_Name中用逗号分隔,如下所示:

预期输出DF

Room_ID        Chamber_ID        Floor_Name
-----------  ------------     ------------------------ 
111,222                 9         X,Y
111                     9 
None                    1 
111,222,333             1 

如何使用熊猫来做到这一点?

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是df.appy()

# Your function would look like this
def GetFloorName(Room_ID, Chamber_ID):
    # Return None If Room_ID is None
    if  Room_ID is None:
        return None

    floor = []
    #split by comma and loop over all 
    for z in Room_ID.split(','):
        floor.append(sqlcall(z,Chamber_ID))
    return ','.join(floor)

#dummy sqlcall
def sqlcall(f,z):
    if z>5:
        return X
    else:
        return Y 

#apply the function on the series
df['Floor_Name'] = df.apply(lambda x:  GetFloorName(x.Room_ID, x.Chamber_ID),axis=1)