Pandas:选择以另一列结尾的列

2024-04-25 13:12:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个脏数据集,其中需要匹配的两列格式不正确:

  • “id”是一个通常由数字组成的字符串,可能以零开头
  • “parent_id”表示行的父项的id,但它已被格式化为int,因此起始零已消失

我想找出哪些行的“id”与“parent\u id”相同。但是,我无法像这样匹配它:

df["is_the_same"] = (df["id"]==df["parent_id"])  

原因其中一些不匹配(例如,id“01004”将“1004”作为父\u id,在这种情况下不匹配)

删除潜在零后,如何选择“id”等于“parent_id”的列

我还尝试:

df["is_the_same"] = df["id"].str.endswith(df["parent_id"])

但似乎.str.endswith只适用于常量字符串(另一列)


Tags: the数据字符串iddfis格式数字
2条回答

将列表理解与endswith一起使用:

df = pd.DataFrame({'id':['01004','1004','54620'], 'parent_id':['1004','203','20']})

df["is_the_same"] = [x.endswith(y) for x, y in df[["id","parent_id"]].values]
#alternative
#df["is_the_same"] = df.apply(lambda x: x["id"].endswith(x["parent_id"]), axis=1)
print (df)
      id parent_id  is_the_same
0  01004      1004         True
1   1004       203        False
2  54620        20         True

如果仅差前导零和数字将转换值与整数进行比较:

df["is_the_same"] = df["id"].astype(int) == df["parent_id"].astype(int)
print (df)
      id parent_id  is_the_same
0  01004      1004         True
1   1004       203        False
2  54620        20        False

使用^{},可以从id列中去掉前导零,然后将其与parent_id列匹配,如下所示:

df["id"].str.lstrip('0') == df["parent_id"]

假设这是df

In [68]: df 
Out[68]: 
      id parent_id
0  01004      1004
1   1004      1004
2    546       100

In [70]: df["is_the_same"] = df["id"].str.lstrip('0') == df["parent_id"]        
In [71]: df    
Out[71]: 
      id parent_id  is_the_same
0  01004      1004         True
1   1004      1004         True
2    546       100        False

相关问题 更多 >