常见问题解答 (FAQ)#
DataFrame 内存使用#
调用 info()
方法时,会显示 DataFrame
的内存使用量(包括索引)。配置选项 display.memory_usage
(参见选项列表)指定了在调用 info()
方法时是否显示 DataFrame
的内存使用量。
例如,调用 info()
方法时,会显示下面 DataFrame
的内存使用量
In [1]: dtypes = [
...: "int64",
...: "float64",
...: "datetime64[ns]",
...: "timedelta64[ns]",
...: "complex128",
...: "object",
...: "bool",
...: ]
...:
In [2]: n = 5000
In [3]: data = {t: np.random.randint(100, size=n).astype(t) for t in dtypes}
In [4]: df = pd.DataFrame(data)
In [5]: df["categorical"] = df["object"].astype("category")
In [6]: df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5000 entries, 0 to 4999
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 int64 5000 non-null int64
1 float64 5000 non-null float64
2 datetime64[ns] 5000 non-null datetime64[ns]
3 timedelta64[ns] 5000 non-null timedelta64[ns]
4 complex128 5000 non-null complex128
5 object 5000 non-null object
6 bool 5000 non-null bool
7 categorical 5000 non-null category
dtypes: bool(1), category(1), complex128(1), datetime64[ns](1), float64(1), int64(1), object(1), timedelta64[ns](1)
memory usage: 288.2+ KB
+
符号表示实际内存使用量可能更高,因为 pandas 不计算 dtype=object
列中值使用的内存。
传递 memory_usage='deep'
将启用更准确的内存使用报告,计算包含对象的完整使用量。这是可选的,因为进行这种深度内省可能成本较高。
In [7]: df.info(memory_usage="deep")
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5000 entries, 0 to 4999
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 int64 5000 non-null int64
1 float64 5000 non-null float64
2 datetime64[ns] 5000 non-null datetime64[ns]
3 timedelta64[ns] 5000 non-null timedelta64[ns]
4 complex128 5000 non-null complex128
5 object 5000 non-null object
6 bool 5000 non-null bool
7 categorical 5000 non-null category
dtypes: bool(1), category(1), complex128(1), datetime64[ns](1), float64(1), int64(1), object(1), timedelta64[ns](1)
memory usage: 424.7 KB
默认情况下,此显示选项设置为 True
,但可以在调用 info()
时通过传递 memory_usage
参数来显式覆盖。
通过调用 memory_usage()
方法可以找到每列的内存使用量。该方法返回一个 Series
,其索引由列名表示,每列的内存使用量以字节为单位显示。对于上面的 DataFrame
,可以使用 memory_usage()
方法找到每列的内存使用量和总内存使用量
In [8]: df.memory_usage()
Out[8]:
Index 128
int64 40000
float64 40000
datetime64[ns] 40000
timedelta64[ns] 40000
complex128 80000
object 40000
bool 5000
categorical 9968
dtype: int64
# total memory usage of dataframe
In [9]: df.memory_usage().sum()
Out[9]: 295096
默认情况下,返回的 Series
中会显示 DataFrame
索引的内存使用量,通过传递 index=False
参数可以抑制索引的内存使用量显示
In [10]: df.memory_usage(index=False)
Out[10]:
int64 40000
float64 40000
datetime64[ns] 40000
timedelta64[ns] 40000
complex128 80000
object 40000
bool 5000
categorical 9968
dtype: int64
info()
方法显示的内存使用量是利用 memory_usage()
方法计算 DataFrame
的内存使用量,同时将输出格式化为人类可读的单位(二进制表示;即 1KB = 1024 字节)。
另请参见 分类数据内存使用。
在 pandas 中使用 if/真值语句#
pandas 遵循 NumPy 约定,当您尝试将某些内容转换为 bool
时会引发错误。这发生在 if
语句中或使用布尔运算 and
、or
和 not
时。以下代码的结果应该是什么是不明确的
>>> if pd.Series([False, True, False]):
... pass
结果应该是 True
,因为它不是零长度,还是 False
,因为存在 False
值?这不明确,因此 pandas 会引发 ValueError
In [11]: if pd.Series([False, True, False]):
....: print("I was true")
....:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-11-5c782b38cd2f> in ?()
----> 1 if pd.Series([False, True, False]):
2 print("I was true")
~/work/pandas/pandas/pandas/core/generic.py in ?(self)
1575 @final
1576 def __nonzero__(self) -> NoReturn:
-> 1577 raise ValueError(
1578 f"The truth value of a {type(self).__name__} is ambiguous. "
1579 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
1580 )
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
您需要明确选择如何处理该 DataFrame
,例如使用 any()
、all()
或 empty()
方法。或者,您可能想比较 pandas 对象是否为 None
。
In [12]: if pd.Series([False, True, False]) is not None:
....: print("I was not None")
....:
I was not None
以下是如何检查是否有任何值为 True
In [13]: if pd.Series([False, True, False]).any():
....: print("I am any")
....:
I am any
按位布尔运算#
位wise 布尔运算符,如 ==
和 !=
,会返回一个布尔类型的 Series
,当与标量比较时,它会执行元素级的比较。
In [14]: s = pd.Series(range(5))
In [15]: s == 4
Out[15]:
0 False
1 False
2 False
3 False
4 True
dtype: bool
有关更多示例,请参阅 布尔比较。
使用 in
运算符#
在 Series
上使用 Python 的 in
运算符会测试成员资格是否在索引中,而不是在值中。
In [16]: s = pd.Series(range(5), index=list("abcde"))
In [17]: 2 in s
Out[17]: False
In [18]: 'b' in s
Out[18]: True
如果此行为让您感到意外,请记住在 Python 字典上使用 in
是测试键,而不是值,而 Series
类似于字典。要测试值中的成员资格,请使用 isin()
方法。
In [19]: s.isin([2])
Out[19]:
a False
b False
c True
d False
e False
dtype: bool
In [20]: s.isin([2]).any()
Out[20]: True
类似地,对于 DataFrame
,in
运算符适用于列轴,测试成员资格是否在列名列表中。
使用用户定义函数 (UDF) 方法进行修改#
本节适用于接受 UDF 的 pandas 方法。特别是方法 DataFrame.apply()
、DataFrame.aggregate()
、DataFrame.transform()
和 DataFrame.filter()
。
在编程中有一条通用规则:不应在迭代容器时修改它。修改会使迭代器失效,导致意外行为。考虑以下示例:
In [21]: values = [0, 1, 2, 3, 4, 5]
In [22]: n_removed = 0
In [23]: for k, value in enumerate(values):
....: idx = k - n_removed
....: if value % 2 == 1:
....: del values[idx]
....: n_removed += 1
....: else:
....: values[idx] = value + 1
....:
In [24]: values
Out[24]: [1, 4, 5]
人们可能期望结果是 [1, 3, 5]
。当使用接受 UDF 的 pandas 方法时,pandas 内部通常会迭代 DataFrame
或其他 pandas 对象。因此,如果 UDF 修改(改变)了 DataFrame
,可能会出现意外行为。
这里有一个使用 DataFrame.apply()
的类似示例
In [25]: def f(s):
....: s.pop("a")
....: return s
....:
In [26]: df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
In [27]: df.apply(f, axis="columns")
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File ~/work/pandas/pandas/pandas/core/indexes/base.py:3805, in Index.get_loc(self, key)
3804 try:
-> 3805 return self._engine.get_loc(casted_key)
3806 except KeyError as err:
File index.pyx:167, in pandas._libs.index.IndexEngine.get_loc()
File index.pyx:196, in pandas._libs.index.IndexEngine.get_loc()
File pandas/_libs/hashtable_class_helper.pxi:7081, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas/_libs/hashtable_class_helper.pxi:7089, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'a'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[27], line 1
----> 1 df.apply(f, axis="columns")
File ~/work/pandas/pandas/pandas/core/frame.py:10374, in DataFrame.apply(self, func, axis, raw, result_type, args, by_row, engine, engine_kwargs, **kwargs)
10360 from pandas.core.apply import frame_apply
10362 op = frame_apply(
10363 self,
10364 func=func,
(...)
10372 kwargs=kwargs,
10373 )
> 10374 return op.apply().__finalize__(self, method="apply")
File ~/work/pandas/pandas/pandas/core/apply.py:916, in FrameApply.apply(self)
913 elif self.raw:
914 return self.apply_raw(engine=self.engine, engine_kwargs=self.engine_kwargs)
--> 916 return self.apply_standard()
File ~/work/pandas/pandas/pandas/core/apply.py:1063, in FrameApply.apply_standard(self)
1061 def apply_standard(self):
1062 if self.engine == "python":
-> 1063 results, res_index = self.apply_series_generator()
1064 else:
1065 results, res_index = self.apply_series_numba()
File ~/work/pandas/pandas/pandas/core/apply.py:1081, in FrameApply.apply_series_generator(self)
1078 with option_context("mode.chained_assignment", None):
1079 for i, v in enumerate(series_gen):
1080 # ignore SettingWithCopy here in case the user mutates
-> 1081 results[i] = self.func(v, *self.args, **self.kwargs)
1082 if isinstance(results[i], ABCSeries):
1083 # If we have a view on v, we need to make a copy because
1084 # series_generator will swap out the underlying data
1085 results[i] = results[i].copy(deep=False)
Cell In[25], line 2, in f(s)
1 def f(s):
----> 2 s.pop("a")
3 return s
File ~/work/pandas/pandas/pandas/core/series.py:5391, in Series.pop(self, item)
5366 def pop(self, item: Hashable) -> Any:
5367 """
5368 Return item and drops from series. Raise KeyError if not found.
5369
(...)
5389 dtype: int64
5390 """
-> 5391 return super().pop(item=item)
File ~/work/pandas/pandas/pandas/core/generic.py:947, in NDFrame.pop(self, item)
946 def pop(self, item: Hashable) -> Series | Any:
--> 947 result = self[item]
948 del self[item]
950 return result
File ~/work/pandas/pandas/pandas/core/series.py:1121, in Series.__getitem__(self, key)
1118 return self._values[key]
1120 elif key_is_scalar:
-> 1121 return self._get_value(key)
1123 # Convert generator to list before going through hashable part
1124 # (We will iterate through the generator there to check for slices)
1125 if is_iterator(key):
File ~/work/pandas/pandas/pandas/core/series.py:1237, in Series._get_value(self, label, takeable)
1234 return self._values[label]
1236 # Similar to Index.get_value, but we do not fall back to positional
-> 1237 loc = self.index.get_loc(label)
1239 if is_integer(loc):
1240 return self._values[loc]
File ~/work/pandas/pandas/pandas/core/indexes/base.py:3812, in Index.get_loc(self, key)
3807 if isinstance(casted_key, slice) or (
3808 isinstance(casted_key, abc.Iterable)
3809 and any(isinstance(x, slice) for x in casted_key)
3810 ):
3811 raise InvalidIndexError(key)
-> 3812 raise KeyError(key) from err
3813 except TypeError:
3814 # If we have a listlike key, _check_indexing_error will raise
3815 # InvalidIndexError. Otherwise we fall through and re-raise
3816 # the TypeError.
3817 self._check_indexing_error(key)
KeyError: 'a'
要解决这个问题,可以创建一个副本,这样修改就不会应用于正在迭代的容器。
In [28]: values = [0, 1, 2, 3, 4, 5]
In [29]: n_removed = 0
In [30]: for k, value in enumerate(values.copy()):
....: idx = k - n_removed
....: if value % 2 == 1:
....: del values[idx]
....: n_removed += 1
....: else:
....: values[idx] = value + 1
....:
In [31]: values
Out[31]: [1, 3, 5]
In [32]: def f(s):
....: s = s.copy()
....: s.pop("a")
....: return s
....:
In [33]: df = pd.DataFrame({"a": [1, 2, 3], 'b': [4, 5, 6]})
In [34]: df.apply(f, axis="columns")
Out[34]:
b
0 4
1 5
2 6
NumPy 类型的缺失值表示#
将 np.nan
用作 NumPy 类型的 NA
表示#
由于 NumPy 和 Python 在底层缺乏对 NA
(缺失值)的支持,NA
本可以表示为:
屏蔽数组方案:一个包含数据的数组和一个布尔值数组,用于指示某个值是否存在或缺失。
使用特殊的标记值、位模式或一组标记值来表示所有 dtypes 中的
NA
。
特殊值 np.nan
(非数字)被选为 NumPy 类型的 NA
值,并且有诸如 DataFrame.isna()
和 DataFrame.notna()
等 API 函数可用于跨不同 dtype 检测 NA 值。然而,这个选择的一个缺点是会将缺失的整数数据强制转换为浮点类型,如 对整数 NA 的支持 中所示。
NumPy 类型的 NA
类型提升#
当通过 reindex()
或其他方式将 NA 引入现有 Series
或 DataFrame
中时,布尔和整数类型将提升到不同的 dtype 以存储 NA。提升规则总结在此表中:
类型类别 |
用于存储 NA 的提升 dtype |
---|---|
|
不变 |
|
不变 |
|
转换为 |
|
转换为 |
对整数 NA
的支持#
由于 NumPy 从底层缺乏高性能的 NA
支持,主要影响是无法在整数数组中表示 NA。例如:
In [35]: s = pd.Series([1, 2, 3, 4, 5], index=list("abcde"))
In [36]: s
Out[36]:
a 1
b 2
c 3
d 4
e 5
dtype: int64
In [37]: s.dtype
Out[37]: dtype('int64')
In [38]: s2 = s.reindex(["a", "b", "c", "f", "u"])
In [39]: s2
Out[39]:
a 1.0
b 2.0
c 3.0
f NaN
u NaN
dtype: float64
In [40]: s2.dtype
Out[40]: dtype('float64')
这种权衡主要是出于内存和性能方面的考虑,同时也为了使结果 Series
保持“数值型”。
如果您需要表示可能带有缺失值的整数,请使用 pandas 或 pyarrow 提供的可空整型扩展 dtypes 之一:
In [41]: s_int = pd.Series([1, 2, 3, 4, 5], index=list("abcde"), dtype=pd.Int64Dtype())
In [42]: s_int
Out[42]:
a 1
b 2
c 3
d 4
e 5
dtype: Int64
In [43]: s_int.dtype
Out[43]: Int64Dtype()
In [44]: s2_int = s_int.reindex(["a", "b", "c", "f", "u"])
In [45]: s2_int
Out[45]:
a 1
b 2
c 3
f <NA>
u <NA>
dtype: Int64
In [46]: s2_int.dtype
Out[46]: Int64Dtype()
In [47]: s_int_pa = pd.Series([1, 2, None], dtype="int64[pyarrow]")
In [48]: s_int_pa
Out[48]:
0 1
1 2
2 <NA>
dtype: int64[pyarrow]
更多信息请参见 可空整型数据类型 和 PyArrow 功能。
为什么不让 NumPy 像 R 一样?#
许多人建议 NumPy 应该模仿更领域特定的统计编程语言 R 中的 NA
支持。部分原因在于 NumPy 的类型层次结构。
相比之下,R 语言只有少数内置数据类型:integer
、numeric
(浮点)、character
和 boolean
。NA
类型是通过为每种类型预留特殊位模式作为缺失值来实现的。虽然在完整的 NumPy 类型层次结构上这样做是可能的,但这将是一个更大的权衡(特别是对于 8 位和 16 位数据类型)和实现工程。
然而,现在可以通过使用屏蔽的 NumPy 类型(例如 Int64Dtype
)或 PyArrow 类型(ArrowDtype
)来获得 R 的 NA
语义。
与 NumPy 的差异#
对于 Series
和 DataFrame
对象,var()
方法通过 N-1
进行标准化,以产生总体方差的无偏估计,而 NumPy 的 numpy.var()
则通过 N 进行标准化,这衡量的是样本方差。请注意,cov()
在 pandas 和 NumPy 中都通过 N-1
进行标准化。
线程安全#
pandas 并非 100% 线程安全。已知问题与 copy()
方法有关。如果您在多个线程之间共享并频繁复制 DataFrame
对象,我们建议在发生数据复制的线程内部持有锁。
更多信息请参见此链接。
字节序问题#
有时您可能需要处理在字节序与您运行 Python 的机器不同的机器上创建的数据。此问题的常见症状是出现类似如下的错误:
Traceback
...
ValueError: Big-endian buffer not supported on little-endian compiler
为了解决这个问题,您应该在将底层 NumPy 数组传递给 Series
或 DataFrame
构造函数之前,使用类似于以下方法将其转换为本地系统字节序:
In [49]: x = np.array(list(range(10)), ">i4") # big endian
In [50]: newx = x.byteswap().view(x.dtype.newbyteorder()) # force native byteorder
In [51]: s = pd.Series(newx)
更多详细信息请参阅NumPy 关于字节序的文档。