繁体   English   中英

在python pandas DataFrames中,设置值时自动进行类型转换的规则是什么?

[英]In python pandas DataFrames, what are the rules for automatic type conversion when setting values?

如果我有一个看起来像的数据框

import pandas

d = pandas.DataFrame( data = {'col1':[100,101,102,103] } )
#   col1
#0   100
#1   101
#2   102
#3   103

而我

d.set_value( 0,'col1', '200')

它将'200'转换为整数:

type( d.col1[0] )
#numpy.int64

但是如果我这样做

d.set_value( 0,'col2', '200')

我懂了

type( d.col2[0] )
#str

如预期的那样。

更多谜团:

另外,说我做以下

[ type(x) for x in d.col1 ]
#[numpy.int64, numpy.int64, numpy.int64, numpy.int64]
d.set_value( [0,1,2,3], 'col1', ['101', '102', '103', 200] )
[ type(x) for x in d.col1 ]
#[str, str, str, str]

因此,即使d.col1原本是整数列,但现在已成为字符串列。 整个列进行此类类型转换的规则是什么?

我只是很好奇在处理熊猫数据框时自动类型转换的规则是什么。

pandas是主要列,并且同一列中的每个元素都必须具有相同的数据类型。

当您使用创建数据框时

import pandas as pd
df = pd.DataFrame({'col':[100,101,102,103]})
df.col.dtype

Out[11]:
dtype('int64')

熊猫会自动推断所有这些输入都是数值并且是整数类型。 因此,当您为此列col设置值时,所有输入将自动转换为当前列dtype int64 ,因此以下内容将为您提供完全相同的输出

df.set_value(0, 'col', '200')  # cast string into int
df.set_value(0, 'col', 200)  # int input
df.set_value(0, 'col', 200.1)  # cast float64 into int64

但是,当您尝试执行df.set_value(0, 'col1', '200') ,当前df没有列col1 ,因此熊猫首先创建了一个名为col1的新列,它将尝试推断此新列的dtype。列根据您的输入。

df.set_value(0, 'col1', '200')
df.col1.dtype  # dtype('O'), means object/string
df.set_value(0, 'col2', 200.1)
df.col2.dtype  # dtype('float64')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM