gpt4 book ai didi

python - 如果列下该行中的任何单元格不是 float ,如何删除 Dataframe 中的行?

转载 作者:行者123 更新时间:2023-12-04 09:28:29 25 4
gpt4 key购买 nike

我有一个数据框,其中有 4 列。现在,这些列下存储的值都是字符串。我想将它们全部转换为 float 。有时,我可能会遇到一个单元格,其中特定列下有一个字符串,在这种情况下,我只想删除整行。例如,考虑以下数据框:

   A.    B.    C.    D 
1. 1. 3. 7
1. 1. 3s 7
1. 1. 3. 7
1. 4s 3. 7
1. 1. 3. 7
1. 1. 3. 7
正如您所看到的,colC 下的第 2 行包含一个无法转换为浮点数的值,在这种情况下,我想删除第二行的所有内容。与 B 列第 4 行相同,我想删除。整排。
所以我想要的输出是:
   A.    B.    C.    D 
1. 1. 3. 7
1. 1. 3. 7
1. 1. 3. 7
1. 1. 3. 7
我删除了第二行和第四行,因为它们包含无法转换为浮点数的值

最佳答案

使用 pd.to_numeric 使用可选参数 errors='coerce'将所有列转换为 numeric键入,然后使用 DataFrame.dropna 删除包含 NaN 的行值(因为无效值将被设置为 NaN ):

df1 = df.apply(pd.to_numeric, errors='coerce').dropna()
结果:
# print(df1)
A. B. C. D
0 1.0 1.0 3.0 7
2 1.0 1.0 3.0 7
4 1.0 1.0 3.0 7
5 1.0 1.0 3.0 7

关于python - 如果列下该行中的任何单元格不是 float ,如何删除 Dataframe 中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62932410/

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