gpt4 book ai didi

python - 从具有非数字索引的数据框中删除行

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:26 25 4
gpt4 key购买 nike

我一直在使用 pandas 对 CSV 文件进行一些有趣的过滤,但遇到了障碍。我正在尝试检查索引列中是否存在乱码文本(非整数)数据,并删除这些行。我尝试在导入时使用条件将它们从数据框中删除,并且之后我尝试迭代它们但没有成功。这是一个例子:

df = pd.read_csv(file, encoding='cp1252').set_index("numbers")
results = df[df["columnA"].str.contains("search_data") & ~df["columnB"].isin(seach_list)]
#I need to add to the above statement to check column "numbers" which I have set to be the index,
#to catch some expected garbled text and filter it out... because it is
#an integer, I can't use str.contains or isdigit or isalnum, I've tried to do len(df["columns"] < 20 , df.index < 20 .... i've tried
#i've tried a few other options at this point as well
# after bringing it in, I've also tried iterating through it:
#
for index, row in results.iterrows():
if not (isinstance( row["numbers"], int )):
print(str(row["numbers"]))
#append whole row to new dataframe
#This also didn't work

对我能做什么有什么想法吗?

Example data in the "numbers columns = 329381432
Example garbled text in "numbers" column that I am
trying to keep from importing: äu$ÒÔ”5$ò"Â$”äu$ÒÔ”5$ò

作为旁注,我必须更改 pd 函数的编码,以便当存在一些非 utf-8 数据时我仍然可以读取文件中的所有好数据...否则会抛出错误导入。

最佳答案

您可以使用pd.to_numericnumbers列转换为数字。所有非数字条目都将被强制为 NaN,然后您可以删除这些行。

df = pd.read_csv(file, encoding='cp1252')
df['numbers'] = pd.to_numeric(df['numbers'], errors='coerce')

df = df.dropna(subset=['numbers']).set_index('numbers')

关于python - 从具有非数字索引的数据框中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46270123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com