python - Pandas DataFrame iloc 破坏了数据类型

标签 python python-3.x pandas

拥有 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 对joinmerge 行为的评论。问题是 A.join(B, on='C') 将在 A 中使用索引并将其与列 B['C'],因为默认情况下连接使用索引。就我而言,我只是使用合并来获得理想的结果。

最佳答案

这符合预期。 pandas 每列跟踪 dtypes。当您调用 testdf.iloc[0] 时,您是在向 pandas 请求一行。它必须将整行转换成一个系列。该行包含一个 float 。因此,作为一个系列的行必须是 float 的。

但是,似乎当 pandas 使用 lociloc 时,它会在您使用单个 __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 使用 lociloc 时,它会进行一些我仍然不完全理解的跨行转换。我确定这与 lociloc 的性质不同于 atiatilocloc 中的 get_value 允许您使用索引数组和 bool 数组访问数据帧。 atiatget_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/

相关文章:

Python 查询对象不可序列化

python-3.x - 将 Picked 或 Joblib 预训练的 ML 模型加载到 Sagemaker 并作为端点托管

python - 在数据框中使用数组对列进行排序

python - 将数据帧的行与同一组合并并将值分配给新列

python - 如何强制指定 Yaml 列表类型

python - 如何从 sklearn SelectKBest 获取实际选择的功能

python - 无法从云存储更改时触发的云功能触发 Composer /气流 dag

Python 显示带有可见超时的通知

python - 如何从 Python 3.5 降级到 Python 3.4

python - Pandas:按名称分组并以最近的日期行