Python Pandas dataframe.infer_objects()
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。
Pandas dataframe.infer_objects()函数试图为输入对象列推断更好的数据类型。这个函数尝试对对象类型的列进行软转换,而对非对象和不可转换的列不作任何改变。推断规则与正常的系列/数据框架构建期间相同。
语法:
DataFrame.infer_objects()
返回:转换:与输入对象类型相同
例子#1:使用infer_objects()函数来推断更好的数据类型。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":["sofia", 5, 8, 11, 100],
"B":[2, 8, 77, 4, 11],
"C":["amy", 11, 4, 6, 9]})
# Print the dataframe
df
输出 :
让我们看看数据框架中每一列的dtype(数据类型)。
# to print the basic info
df.info()
正如我们在输出中看到的,第一和第三列是对象类型,而第二列是int64类型。现在将数据框架切片,并从中创建一个新的数据框架。
# slice from the 1st row till end
df_new = df[1:]
# Let's print the new data frame
df_new
# Now let's print the data type of the columns
df_new.info()
输出 :
正如我们在输出中看到的,列 “A “和 “C “是对象类型的,尽管它们包含整数值。所以,让我们试试infer_objects()函数。
# applying infer_objects() function.
df_new = df_new.infer_objects()
# Print the dtype after applying the function
df_new.info()
输出 :
现在,如果我们看一下每一列的dtype,我们可以看到 “A “和 “C “列现在是int64类型。
例子#2:使用infer_objects()函数来推断对象的更好的数据类型。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":["sofia", 5, 8, 11, 100],
"B":[2 + 2j, 8, 77, 4, 11],
"C":["amy", 11, 4, 6, 9]})
# Print the dataframe
df
让我们看看数据框架中每一列的dtype(数据类型)。
# to print the basic info
df.info()
正如我们在输出中看到的,第一和第三列是对象类型,而第二列是complex128类型。现在将数据框架切片,并从中创建一个新的数据框架。
# slice from the 1st row till end
df_new = df[1:]
# Let's print the new data frame
df_new
# Now let's print the data type of the columns
df_new.info()
正如我们在输出中看到的,列 “A “和 “C “是对象类型的,尽管它们包含整数值。列 “B “的情况也是如此。所以,让我们试试infer_objects()函数。
# applying infer_objects() function.
df_new = df_new.infer_objects()
# Print the dtype after applying the function
df_new.info()
输出 :
注意,列 “B “的dtype没有改变。 infer_objects()函数试图进行软转换,使非对象和不可转换的列保持不变。