拥有 Pandas 0.19.2。
这是一个例子:
testdf = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [1.0, 2.0, 3.0, 4.0]})
testdf.dtypes
输出:
A int64
B float64
dtype: object
现在一切看起来都很好,但我不喜欢的是(注意,第一个调用是 pd.Series.iloc
,第二个是 pd.DataFrame。伊洛克
)
print(type(testdf.A.iloc[0]))
print(type(testdf.iloc[0].A))
输出:
<class 'numpy.int64'>
<class 'numpy.float64'>
我在试图理解为什么 pd.DataFrame.join()
操作几乎没有返回两个 int64
列的交集时发现了它,而应该有很多。
我的猜测是因为类型不一致可能与此行为有关,但我不确定......我的简短调查揭示了上面的事情,现在我有点困惑。
如果有人知道如何解决它 - 我将非常感谢任何提示!
UPD
感谢@EdChum 的评论。所以这是我生成的数据和加入/合并行为的示例
testdf.join(testdf, on='A', rsuffix='3')
A B A3 B3
0 1 1.0 2.0 2.0
1 2 2.0 3.0 3.0
2 3 3.0 4.0 4.0
3 4 4.0 NaN NaN
和什么才算完全一样
pd.merge(left=testdf, right=testdf, on='A')
返回
A B_x B_y
0 1 1.0 1.0
1 2 2.0 2.0
2 3 3.0 3.0
3 4 4.0 4.0
UPD2 复制@EdChum 对join
和merge
行为的评论。问题是 A.join(B, on='C')
将在 A
中使用索引并将其与列 B['C']
,因为默认情况下连接使用索引。就我而言,我只是使用合并来获得理想的结果。
最佳答案
这符合预期。 pandas
每列跟踪 dtypes
。当您调用 testdf.iloc[0]
时,您是在向 pandas 请求一行。它必须将整行转换成一个系列。该行包含一个 float 。因此,作为一个系列的行必须是 float 的。
但是,似乎当 pandas 使用 loc
或 iloc
时,它会在您使用单个 __getitem__
这里有一些有趣的 testdf
测试用例,只有一个 int
列
testdf = pd.DataFrame({'A': [1, 2, 3, 4]})
print(type(testdf.iloc[0].A))
print(type(testdf.A.iloc[0]))
<class 'numpy.int64'>
<class 'numpy.int64'>
改成OP测试用例
testdf = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [1.0, 2.0, 3.0, 4.0]})
print(type(testdf.iloc[0].A))
print(type(testdf.A.iloc[0]))
<class 'numpy.float64'>
<class 'numpy.int64'>
print(type(testdf.loc[0, 'A']))
print(type(testdf.iloc[0, 0]))
print(type(testdf.at[0, 'A']))
print(type(testdf.iat[0, 0]))
print(type(testdf.get_value(0, 'A')))
<class 'numpy.float64'>
<class 'numpy.float64'>
<class 'numpy.int64'>
<class 'numpy.int64'>
<class 'numpy.int64'>
因此,似乎当 pandas
使用 loc
或 iloc
时,它会进行一些我仍然不完全理解的跨行转换。我确定这与 loc
和 iloc
的性质不同于 at
、iat
,iloc
和 loc
中的 get_value
允许您使用索引数组和 bool 数组访问数据帧。 at
、iat
和 get_value
一次只能访问一个单元格。
尽管如此
testdf.loc[0, 'A'] = 10
print(type(testdf.at[0, 'A']))
当我们通过 loc
分配给该位置时,pandas
确保 dtype
保持一致。
关于python - Pandas DataFrame iloc 破坏了数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662881/