Python 熊猫是一种神秘的行为
我正在编写一些单元测试,但是当数据帧在各个方面都相等时,它总是失败。经过调查,我发现Python 熊猫是一种神秘的行为,python,pandas,dataframe,Python,Pandas,Dataframe,我正在编写一些单元测试,但是当数据帧在各个方面都相等时,它总是失败。经过调查,我发现 a.equals( a[ a.columns ] ) 为false,其中a是我手动创建的数据帧。有什么原因呢 编辑: 我发现问题与使用混合类型列表创建df有关: a = pd.DataFrame( [['a',1],['b',2]] ) 尽管列表是混合的,但列的数据类型是正确的。我认为您可以使用pd.util.testing.assert\u frame\u equal()方法: In [15]: help
a.equals( a[ a.columns ] )
为false,其中a是我手动创建的数据帧。有什么原因呢
编辑:
我发现问题与使用混合类型列表创建df有关:
a = pd.DataFrame( [['a',1],['b',2]] )
尽管列表是混合的,但列的数据类型是正确的。我认为您可以使用
pd.util.testing.assert\u frame\u equal()
方法:
In [15]: help(pd.util.testing.assert_frame_equal)
Help on function assert_frame_equal in module pandas.util.testing:
assert_frame_equal(left, right, check_dtype=True, check_index_type='equiv', check_column_type='equiv', check_frame_type=True, check_less_precise
False, check_names=True, by_blocks=False, check_exact=False, check_datetimelike_compat=False, check_like=False, obj='DataFrame')
Check that left and right DataFrame are equal.
Parameters
----------
left : DataFrame
right : DataFrame
check_dtype : bool, default True
Whether to check the DataFrame dtype is identical.
check_index_type : bool / string {'equiv'}, default False
Whether to check the Index class, dtype and inferred_type
are identical.
check_column_type : bool / string {'equiv'}, default False
Whether to check the columns class, dtype and inferred_type
are identical.
check_frame_type : bool, default False
Whether to check the DataFrame class is identical.
check_less_precise : bool, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
check_names : bool, default True
Whether to check the Index names attribute.
by_blocks : bool, default False
Specify how to compare internal data. If False, compare by columns.
If True, compare by blocks.
check_exact : bool, default False
Whether to compare number exactly.
check_dateteimelike_compat : bool, default False
Compare datetime-like which is comparable ignoring dtype.
check_like : bool, default False
If true, then reindex_like operands
obj : str, default 'DataFrame'
Specify object name being compared, internally used to show appropriate
assertion message
如果希望1.0==1,请使用
检查\u dtype=False
,因为在这种情况下,由于不同的数据类型,此方法将返回False数据帧列类型不同
a = pd.DataFrame( [['a',1],['b',2]] )
print type(a[ a.columns ].columns)
print type(a.columns)
<class 'pandas.indexes.numeric.Int64Index'>
<class 'pandas.indexes.range.RangeIndex'>
a=pd.DataFrame([[a',1],[b',2]]
打印类型(a[a.columns].列)
打印类型(a.列)
而且
print type(a[ a.columns ].columns[0])
print type(a.columns[0])
<type 'numpy.int64'>
<type 'int'>
打印类型(a[a.columns].列[0])
打印类型(a.列[0])
最好确保列类型相同。我测试它,它在我的df
a=pd.DataFrame({'a':[1,2,3],'B':[4,5,6],'C':[7,8,9],'D':[1,3,5],'E':[5,3,6],'F':[7,4,3])print(a)
.jezrael,好吧,它应该永远是真的,所以我想知道是什么导致它是假的。你能分享复制这个的样本数据吗?