使用 MultiIndex 访问 Pandas DataFrame 中的单元格会丢失类型信息 [英] Accessing a cell in a pandas DataFrame with MultiIndex loses type information

查看:39
本文介绍了使用 MultiIndex 访问 Pandas DataFrame 中的单元格会丢失类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 MultiIndex 创建一个 pandas DataFrame 时,访问单个单元格会丢失类型信息:

When I create a pandas DataFrame with MultiIndex, accessing a single cell loses type information:

df2 = pd.DataFrame([{"a":1.0,"b":2,"c":3,"d":4}]).set_index(["c","d"])

df2.dtypes

a    float64
b      int64
dtype: object

df2.loc[(3,4),"b"] 返回 2.0 类型 numpy.float64 而不是 2 类型 numpy.int64.

but df2.loc[(3,4),"b"] returns 2.0 of type numpy.float64 instead of 2 of type numpy.int64.

参见

df1 = pd.DataFrame([{"a":1.0,"b":2,"c":3}]).set_index("c")

其中 df1.loc[3,"b"] 返回 2 类型 numpy.int64 .

where df1.loc[3,"b"] returns 2 of type numpy.int64 .

这是一个错误还是我做错了什么?

Is this a bug or am I doing something wrong?

注意:at(用于代替loc)为两个df1返回正确类型的值和 df2.

NB: at (used instead of loc) returns the value of the correct type for both df1 and df2.

推荐答案

我的意见 - 可能,但不是很好:

My opinion - possible, but not nice:

a = df2.loc[[(3,4)],"b"].iat[0]
print (a)
2

这篇关于使用 MultiIndex 访问 Pandas DataFrame 中的单元格会丢失类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆