整数格式规范'd'在逐行应用于pandas DataFrame中的numpy.int列时会产生ValueError。>

问题描述 投票:0回答:1

假设我创建一个同时包含intfloat类型的熊猫数据框:

>>> df=pd.DataFrame([[1, 1.3], [2, 2.4]], columns=['a', 'b'])
>>> df
   a    b
0  1  1.3
1  2  2.4

很明显列'a'numpy.int64值组成:

>>> df.a.dtype
dtype('int64')
>>> df.a[0]
1
>>> type(df.a[0])
<class 'numpy.int64'>

...并且我可以使用d格式说明符来格式化这些'a'列的值:

>>> "{a:d}".format(a=df.a[0])
'1'

但是,如果我尝试逐行应用相同的格式,则会收到此错误,指出'a'列中的值是浮点数而不是整数:

>>> df.apply(lambda s: "{a:d}{b:f}".format(**s), axis=1)
Traceback (most recent call last):
...
ValueError: ("Unknown format code 'd' for object of type 'float'", 'occurred at index 0')

这里发生了什么?

假设我创建一个同时包含int和float类型的熊猫数据框:>>> df = pd.DataFrame([[1,1.3],[2,2.4]],columns = ['a','b']) >>> df ab 0 1 1.3 1 2 2.4很显然...

python pandas
1个回答
0
投票
df.apply(lambda x: ( type(x['a']),type(x['b']) ),axis=1)
0    (<class 'numpy.float64'>, <class 'numpy.float6...
1    (<class 'numpy.float64'>, <class 'numpy.float6...
dtype: object
© www.soinside.com 2019 - 2024. All rights reserved.