目录
421、pandas.DataFrame.infer_objects方法
424、pandas.DataFrame.to_numpy方法
一、用法精讲
421、pandas.DataFrame.infer_objects方法
421-1、语法
# 421、pandas.DataFrame.infer_objects方法
pandas.DataFrame.infer_objects(copy=None)
Attempt to infer better dtypes for object columns.
Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction.
Parameters:
copybool, default True
Whether to make a copy for non-object or non-inferable columns or Series.
Note
The copy keyword will change behavior in pandas 3.0. Copy-on-Write will be enabled by default, which means that all methods with a copy keyword will use a lazy copy mechanism to defer the copy and ignore the copy keyword. The copy keyword will be removed in a future version of pandas.
You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = True
Returns:
same type as input object.
421-2、参数
421-2-1、copy(可选,默认值为None):布尔值,决定是否在执行推断操作时创建数据的副本。如果设置为True
,则会返回一个新的DataFrame
,其推断后的类型会应用到新的对象上,原始的DataFrame
不会被修改;如果设置为False
,则推断的类型会直接在原始的DataFrame
上进行修改。若设置为None
(默认值),函数会决定是否创建副本,这个决定可能依赖于底层实现,通常情况下会在需要时创建副本。
421-3、功能
用于从数据类型为object
的列中推断出更具体的数据类型。例如,如果某一列中实际存储的是整数或浮点数,但由于某些原因被读取为object
类型,这个方法就可以尝试将其转化为int64
或float64
类型。
421-4、返回值
返回一个DataFrame
,其object
类型的列被尝试推断为更具体的类型,如果copy=True
,返回的是一个新的DataFrame
;否则,原始DataFrame
将被修改并返回。
421-5、说明
无
421-6、用法
421-6-1、数据准备
无
421-6-2、代码示例
# 421、pandas.DataFrame.infer_objects方法
import pandas as pd
# 创建一个DataFrame,其中的某些列被推断为object类型
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4.0, 5.1, 6.2],
'C': ['2022-01-01', '2023-01-01', '2024-01-01']
}, dtype='object')
# 使用infer_objects来推断更具体的类型
df_inferred = df.infer_objects()
print(df_inferred.dtypes)
421-6-3、结果输出
# 421、pandas.DataFrame.infer_objects方法
# A int64
# B float64
# C object
# dtype: object
422、pandas.DataFrame.copy方法
422-1、语法
# 422、pandas.DataFrame.copy方法
pandas.DataFrame.copy(deep=True)
Make a copy of this object’s indices and data.
When deep=True (default), a new object will be created with a copy of the calling object’s data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below).
When deep=False, a new object will be created without copying the calling object’s data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa).
Note
The deep=False behaviour as described above will change in pandas 3.0. Copy-on-Write will be enabled by default, which means that the “shallow” copy is that is returned with deep=False will still avoid making an eager copy, but changes to the data of the original will no longer be reflected in the shallow copy (or vice versa). Instead, it makes use of a lazy (deferred) copy mechanism that will copy the data only when any changes to the original or shallow copy is made.
You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = True
Parameters:
deep
bool, default True
Make a deep copy, including a copy of the data and the indices. With deep=False neither the indices nor the data are copied.
Returns:
Series or DataFrame
Object type matches caller.
Notes
When deep=True, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to copy.deepcopy in the Standard Library, which recursively copies object data (see examples below).
While Index objects are copied when deep=True, the underlying numpy array is not copied for performance reasons. Since Index is immutable, the underlying data can be safely shared and a copy is not needed.
Since pandas is not thread safe, see the gotchas when copying in a threading environment.
When copy_on_write in pandas config is set to True, the copy_on_write config takes effect even when deep=False. This means that any changes to the copied data would make a new copy of the data upon write (and vice versa). Changes made to either the original or copied variable would not be reflected in the counterpart. See Copy_on_Write for more information.
422-2、参数
422-2-1、deep(可选,默认值为True):布尔值,该参数决定是否执行深复制(deep copy
):
- deep=True(默认值):进行深复制,这意味着副本和原始
DataFrame
的数据将独立存储,改变副本中的数据不会影响原始DataFrame
,反之亦然。 - deep=False:进行浅复制,这意味着副本和原始
DataFrame
共享数据存储空间,改变副本中的数据可能会影响原始DataFrame
,反之亦然。
422-3、功能
用于生成现有DataFrame
的一个副本,它允许用户选择进行深复制还是浅复制,从而根据需要选择合适的数据复制方式:
- 深复制(
deep copy
):创建DataFrame
和其数据的完整拷贝,包括数据、索引等,确保副本和原始对象完全独立。 - 浅复制(
shallow copy
):创建DataFrame
的新引用,但不复制数据本身,因此两者共享相同的底层数据存储空间。
422-4、返回值
返回一个新的DataFrame
对象,对于深复制,这个新对象是对原始DataFrame
的完全独立的拷贝;对于浅复制,这个新对象与原始DataFrame
共享相同的数据。
422-5、说明
无
422-6、用法
422-6-1、数据准备
无
422-6-2、代码示例
# 422、pandas.DataFrame.copy方法
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4.0, 5.1, 6.2]
})
# 执行深复制(默认行为)
df_deep_copy = df.copy()
df_deep_copy.iloc[0, 0] = 10 # 修改深复制的DataFrame中的数据
print("Original DataFrame:")
print(df)
print("\nDeep Copy DataFrame:")
print(df_deep_copy)
# 执行浅复制
df_shallow_copy = df.copy(deep=False)
df_shallow_copy.iloc[0, 0] = 10 # 修改浅复制的DataFrame中的数据
print("\nOriginal DataFrame after shallow copy modification:")
print(df)
print("\nShallow Copy DataFrame:")
print(df_shallow_copy)
422-6-3、结果输出
# 422、pandas.DataFrame.copy方法
# Original DataFrame:
# A B
# 0 1 4.0
# 1 2 5.1
# 2 3 6.2
#
# Deep Copy DataFrame:
# A B
# 0 10 4.0
# 1 2 5.1
# 2 3 6.2
#
# Original DataFrame after shallow copy modification:
# A B
# 0 10 4.0
# 1 2 5.1
# 2 3 6.2
#
# Shallow Copy DataFrame:
# A B
# 0 10 4.0
# 1 2 5.1
# 2 3 6.2
423、pandas.DataFrame.bool方法
423-1、语法
# 423、pandas.DataFrame.bool方法
pandas.DataFrame.bool()
Return the bool of a single element Series or DataFrame.
Deprecated since version 2.1.0: bool is deprecated and will be removed in future version of pandas. For Series use pandas.Series.item.
This must be a boolean scalar value, either True or False. It will raise a ValueError if the Series or DataFrame does not have exactly 1 element, or that element is not boolean (integer values 0 and 1 will also raise an exception).
Returns:
bool
The value in the Series or DataFrame.
423-2、参数
无
423-3、功能
用于将DataFrame
转换为布尔上下文,但它仅适用于包含单个元素(一个值)的DataFrame
。换句话说,只有在DataFrame
中包含一个元素的情况下,该方法才会返回该元素的布尔值;否则,它会引发ValueError
。
423-4、返回值
如果DataFrame
中唯一的元素的布尔值为True
,则返回True
;否则返回False
。
423-5、说明
无
423-6、用法
423-6-1、数据准备
无
423-6-2、代码示例
# 423、pandas.DataFrame.bool方法
import pandas as pd
# 创建一个包含单个元素的DataFrame
df_single = pd.DataFrame({'A': [True]})
# 将DataFrame转换为布尔值
try:
result = df_single.bool()
print("The boolean value of the DataFrame is:", result)
except ValueError as e:
print('Error:', e)
# 创建一个包含多个元素的DataFrame
df_multiple = pd.DataFrame({'A': [True, False]})
# 尝试将包含多个元素的DataFrame转换为布尔值
try:
result = df_multiple.bool()
print("The boolean value of the DataFrame is:", result)
except ValueError as e:
print('Error:', e)
# 创建一个包含超过一个元素的DataFrame
df_multiple_elements = pd.DataFrame({'A': [5]})
# 尝试将单个非布尔值元素的DataFrame转换为布尔值
try:
result = df_multiple_elements.bool()
print("The boolean value of the DataFrame is:", result)
except ValueError as e:
print('Error:', e)
423-6-3、结果输出
# 423、pandas.DataFrame.bool方法
# The boolean value of the DataFrame is: True
# Error: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
# Error: bool cannot act on a non-boolean single element DataFrame
424、pandas.DataFrame.to_numpy方法
424-1、语法
# 424、pandas.DataFrame.to_numpy方法
panas.DataFrame.to_numpy(dtype=None, copy=False, na_value=_NoDefault.no_default)
Convert the DataFrame to a NumPy array.
By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are float16 and float32, the results dtype will be float32. This may require copying data and coercing values, which may be expensive.
Parameters:
dtype
str or numpy.dtype, optional
The dtype to pass to numpy.asarray().
copy
bool, default False
Whether to ensure that the returned value is not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary.
na_value
Any, optional
The value to use for missing values. The default value depends on dtype and the dtypes of the DataFrame columns.
Returns:
numpy.ndarray
424-2、参数
424-2-1、dtype(可选,默认值为None):指定生成数组的目标数据类型,如果未指定,默认情况下会保留数据的原始类型,可以通过该参数改变所有数据的类型,例如将所有元素转换为浮点型 (float
)或整型(int
)。
424-2-2、copy(可选,默认值为False):是否强制复制数据,如果设置为False
,则在可能的情况下,不会创建数据的副本,而是返回数据的视图(引用);如果设置为True
,则始终会复制数据,并返回新的数组。
424-2-3、na_value(可选):在生成的数组中,用于替换缺失值(NaN)的值,如果未指定此参数,缺失值将保留为原来的形式(通常为NaN
或者None
),指定此参数可以将所有缺失值替换为一个指定的值。
424-3、功能
将DataFrame
中的数据转换并返回为numpy.ndarray
,这对于需要进行高效的数值计算和数组操作非常有用。
424-4、返回值
返回一个numpy.ndarray对象,对象中每个元素对应DataFrame
中的值。数据类型、元素值和是否复制数据都取决于传递给该方法的参数。
424-5、说明
无
424-6、用法
424-6-1、数据准备
无
424-6-2、代码示例
# 424、pandas.DataFrame.to_numpy方法
import pandas as pd
import numpy as np
# 创建一个示例DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7.1, 8.2, np.nan]
})
# 默认转换为NumPy数组
array_default = df.to_numpy()
print("Default conversion to NumPy array:")
print(array_default)
# 指定数据类型为float32
array_float32 = df.to_numpy(dtype='float32')
print("\nConversion to NumPy array with dtype='float32':")
print(array_float32)
# 强制复制数据
array_copy = df.to_numpy(copy=True)
print("\nConversion to NumPy array with copy=True:")
print(array_copy)
# 替换缺失值NaN为0
array_na_value = df.to_numpy(na_value=0)
print("\nConversion to NumPy array with na_value=0:")
print(array_na_value)
424-6-3、结果输出
# 424、pandas.DataFrame.to_numpy方法
# Default conversion to NumPy array:
# [[1. 4. 7.1]
# [2. 5. 8.2]
# [3. 6. nan]]
#
# Conversion to NumPy array with dtype='float32':
# [[1. 4. 7.1]
# [2. 5. 8.2]
# [3. 6. nan]]
#
# Conversion to NumPy array with copy=True:
# [[1. 4. 7.1]
# [2. 5. 8.2]
# [3. 6. nan]]
#
# Conversion to NumPy array with na_value=0:
# [[1. 4. 7.1]
# [2. 5. 8.2]
# [3. 6. 0. ]]
425、pandas.DataFrame.head方法
425-1、语法
# 425、pandas.DataFrame.head方法
pandas.DataFrame.head(n=5)
Return the first n rows.
This function returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it.
For negative values of n, this function returns all rows except the last |n| rows, equivalent to df[:n].
If n is larger than the number of rows, this function returns all rows.
Parameters:
n
int, default 5
Number of rows to select.
Returns:
same type as caller
The first n rows of the caller object.
425-2、参数
425-2-1、n(可选,默认值为5):整数,指定返回的行数,如果未提供,该方法默认返回前5行。
425-3、功能
用于返回一个DataFrame的前n
行,默认返回前5行,这在预览数据内容时非常有用,特别是当你想要查看一个DataFrame的前几行以便了解数据的结构和内容时。
425-4、返回值
返回一个pandas.DataFrame对象,对象包含前n
行。
425-5、说明
425-5-1、数据预览:当读入一个新的数据集时,快速查看前几行数据。
425-5-2、调试和检查:在数据处理过程中的不同步骤,检查中间数据的内容和格式。
425-5-3、报告和展示:在展示数据时,只需要展示前几行数据以保持简洁和清晰。
425-6、用法
425-6-1、数据准备
无
425-6-2、代码示例
# 425、pandas.DataFrame.head方法
import pandas as pd
# 创建一个示例DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace'],
'Age': [24, 30, 22, 25, 29, 32, 27],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio']
}
df = pd.DataFrame(data)
# 使用head方法查看前5行
print("前5行:")
print(df.head())
# 使用head方法查看前3行
print("\n前3行:")
print(df.head(n=3))
425-6-3、结果输出
# 425、pandas.DataFrame.head方法
# 前5行:
# Name Age City
# 0 Alice 24 New York
# 1 Bob 30 Los Angeles
# 2 Charlie 22 Chicago
# 3 David 25 Houston
# 4 Eve 29 Phoenix
#
# 前3行:
# Name Age City
# 0 Alice 24 New York
# 1 Bob 30 Los Angeles
# 2 Charlie 22 Chicago