使用字母数字列表中的 .loc 和 asin 过滤 DataFrame

发布于 2025-01-16 21:03:23 字数 1086 浏览 6 评论 0原文

我正在尝试使用包含字母数字值的列表来过滤数据框。下面是一个示例数据框:

AB
D010252
Patient150
D517571
DaysWorked12

我创建了一个名为“codes”的列表:

codes = ['D0102', 'D5175']

我使用的代码如下所示,数据框没有提取任何内容:

new_df= df.loc[df['A'].isin(codes)]

所需的输出我要显示的数据框是这样的:

AB
D010252
D517571

当我将名为“codes”的列表更改为:

codes = ['Patients', 'DaysWorked']

I使用同一行代码:

new_df= df.loc[df['A'].isin(codes)]

新数据框提取了正确的数据:

AB
患者150
DaysWorked12

I am trying to filter a dataframe using a list with alphanumerical values. Here is a sample dataframe below:

AB
D010252
Patients150
D517571
DaysWorked12

I created a list named "codes" to:

codes = ['D0102', 'D5175']

The code I used is shown below and the dataframe didn't pull up anything:

new_df= df.loc[df['A'].isin(codes)]

The desired output dataframe that I want to display is this:

AB
D010252
D517571

When I changed the list named "codes" to:

codes = ['Patients', 'DaysWorked']

I used the same line of code:

new_df= df.loc[df['A'].isin(codes)]

The new dataframe pulled the correct data:

AB
Patients150
DaysWorked12

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萝莉病 2025-01-23 21:03:23

dfA 列中很可能存在一些不需要的空格。你可能想这样做:

df.loc[df['A'].str.strip().isin(codes)]

There's a good chance that the column A of your df might have some unwanted whitespaces in it. You might wanna do this:

df.loc[df['A'].str.strip().isin(codes)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文