我有一个数据帧,其中我有非常不同类型的条目(文本、整数、浮点数、时间等),我正在try 删除文本条目中的前导和尾随空格,以便我的其他代码可以按预期工作.然而,我的代码似乎不起作用.
下面是我想要做的一个简单的例子:
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
正如您所看到的,df1
和df2
具有完全相同的整体(NaN),但是代码块print(cell1==cell2)
声称这些单元是不同的.
这是怎么回事?