python - 如何从两个不同的列表中删除重复项,一个只包含 int,另一个包含混合的 int 和 str?
问题描述
我有一个带有一些列的 df。列表中的条目应根据其中两列进行过滤/删除其重复项:其中一列仅包含数字,而另一列包含混合字符串(字母 + 数字)和数字。
我想做的是:将第一列中的数字与:
第二列中每个字符串末尾的数字(总是最后 X 个字符)
第二列中的数字,然后删除重复的条目。
条目要么在其中一列中有信息,要么有一个空字符串。
例子:
Col 1 | Col 2 | Col 3
ABC. | 12345 | ""
DEF. | "" | DEF12345
GHI. | "" | 12345
如您所见,我们有 3 个不同的条目。我想根据第 2 列和第 3 列进行过滤。
提前非常感谢!
解决方案
假设您的 DataFrame 是:
df = pd.DataFrame(
{
'Col 1':['ABC', 'DEF', 'GHI'],
'Col 2':[12345, '', ''],
'Col 3':['','DEF12345', 12345]
}
)
print(df)
Col 1 Col 2 Col 3
0 ABC 12345
1 DEF DEF12345
2 GHI 12345
您必须构建一个自定义函数来正确解析和转换值,然后将其应用于您想要的列。
鉴于您的问题不够清晰,在这里我只能做一个虚拟示例,您必须对其进行修改以使其适用于您的实际情况。
def str_to_int(val):
if type(val) is int:
return val
elif type(val) is str:
if val == '':
return 0 #you have to choose how to deal with this
else:
return int(val[3:]) #assuming you have always 3 letters before the number
df['Col 2'] = df['Col 2'].apply(str_to_int)
df['Col 3'] = df['Col 3'].apply(str_to_int)
print(df)
Col 1 Col 2 Col 3
0 ABC 12345 0
1 DEF 0 12345
2 GHI 0 12345
现在您可以轻松找到重复项,因为所有条目都是数字。
#Make a new column that keeps only the non 0 integers
def exclude_zeros(row):
return row['Col 2'] or row['Col 3']
df['Col 4'] = df.apply(exclude_zeros, axis=1)
#Remove the duplicates and keep only the relevant data
df = df.drop_duplicates(subset='Col 4', keep='first')[['Col 1', 'Col 4']]
print(df)
Col 1 Col 4
0 ABC 12345
推荐阅读
- shopify - 使用字符串创建 Liquid 变量
- c# - Unity C# 向围绕移动轴旋转的目标发射弹丸
- java - 创建用户时的 Android Firebase 错误
- angular - 角度模板 *ngIf 与数组比较
- reporting-services - SSRS 报告从 rdl 运行时未返回所有记录
- reactjs - Reactstrap 模态窗口未显示
- python - Django 在远程服务器中找不到文件
- java - TableView 不会返回 sqlite 数据
- android - 已连接网络上的活动 Internet 连接
- mysql - 带有 WHERE 语句的 SQL SELECT MIN 值