python-3.x 在pandas中将strip()Map到字符串并没有改变NaN条目,但仍然声称它们是不同的?

c0vxltue  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(134)

我有一个嵌套框架,其中有非常不同的条目(文本,整数,浮点数,时间等),我试图删除文本条目中的前导和尾随空格,以便我的其他代码可以按预期工作。然而,我的代码似乎不工作。
这里有一个简单的例子,我正在尝试做什么:

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.array(([np.nan, 2, 3], [4, 5, 6])), columns=["one", "two", "three"])
print(df1)
print("")
df2 = df1.map(lambda x: x.strip() if isinstance(x, str) else x)
print(df2)
print("")
print(df1==df2)
print("")
cell1 = df1.at[0, "one"]
cell2 = df2.at[0, "one"]
print(cell1, type(cell1))
print(cell2, type(cell2))
print(cell1==cell2)

字符串
当我运行这段代码时,输出是:

one  two  three
0  NaN  2.0    3.0
1  4.0  5.0    6.0

   one  two  three
0  NaN  2.0    3.0
1  4.0  5.0    6.0

     one   two  three
0  False  True   True
1   True  True   True

nan <class 'numpy.float64'>
nan <class 'numpy.float64'>
False


正如你所看到的,df1df2具有完全相同的整数(NaN),但是代码块print(cell1==cell2)声称这些单元格是不同的。
这是怎么回事?

odopli94

odopli941#

这就是浮点数的工作原理,你不能直接比较NaN s(Why is NaN not equal to NaN?
使用Dataframe.equals比较两个字符串:

df1 = pd.DataFrame(
    np.array(([np.nan, 2, 3], [4, 5, 6])), columns=["one", "two", "three"]
)

df2 = df1.map(lambda x: x.strip() if isinstance(x, str) else x)

print(df1.equals(df2))

字符串
印刷品:

True

相关问题