如何从给定的数据帧列中删除所有字符串?

发布于 2025-01-25 10:47:15 字数 172 浏览 2 评论 0原文

我需要在Python中预处以用于机器学习的列。该列包含一系列的1和0(这是所需的输出),但是其中有一些字符串需要删除['px7','d1'等。]

我考虑过将DF.Replace用于用np.nan替换字符串,然后使用df.dropna()将其删除。我想知道这样做的标准方法是什么,因为这可能是一项非常常见的预处理任务。

I need to preprocess a column for machine learning in python. The column contains a series of 1s and 0s (which is the desired output), but there are some strings in there that needs to be removed ['PX7','D1', etc..]

I thought about using df.replace to replace the strings with np.nan and then using df.dropna() to remove it. I was wondering what is the standard way of doing this given that this is probably a very common preprocessing task.

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

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

发布评论

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

评论(2

玉环 2025-02-01 10:47:15

您可以使用:

df2 = df.where(df.isin([0,1]))

或者,转换为数字以保持所有数字:

df2 = df.apply(pd.to_numeric, errors='coerce')

然后,您可以使用dropna(如果需要)。

You can use:

df2 = df.where(df.isin([0,1]))

Or, convert to numeric to keep all numbers:

df2 = df.apply(pd.to_numeric, errors='coerce')

Then you can use dropna the way you want (if needed).

∞梦里开花 2025-02-01 10:47:15

使用:

df[df['col'].str.isdigit().fillna(True)]

输入:

“在此处输入图像描述”

输出:

df[df['col'].isin([0,1])]

Use:

df[df['col'].str.isdigit().fillna(True)]

Input:

enter image description here

Output:

enter image description here

Second approch:

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