常见问题 (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/真值语句#
当你尝试将某些内容转换为 bool
类型时,pandas 遵循 NumPy 的约定,会引发错误。这发生在 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
位布尔运算#
位布尔运算符,如 ==
和 !=
,在与标量进行比较时,会返回一个布尔型 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:3812, in Index.get_loc(self, key)
3811 try:
-> 3812 return self._engine.get_loc(casted_key)
3813 except KeyError as err:
File ~/work/pandas/pandas/pandas/_libs/index.pyx:167, in pandas._libs.index.IndexEngine.get_loc()
File ~/work/pandas/pandas/pandas/_libs/index.pyx:196, in pandas._libs.index.IndexEngine.get_loc()
File pandas/_libs/hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas/_libs/hashtable_class_helper.pxi:7096, 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:10381, in DataFrame.apply(self, func, axis, raw, result_type, args, by_row, engine, engine_kwargs, **kwargs)
10367 from pandas.core.apply import frame_apply
10369 op = frame_apply(
10370 self,
10371 func=func,
(...)
10379 kwargs=kwargs,
10380 )
> 10381 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:5402, in Series.pop(self, item)
5377 def pop(self, item: Hashable) -> Any:
5378 """
5379 Return item and drops from series. Raise KeyError if not found.
5380
(...)
5400 dtype: int64
5401 """
-> 5402 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:1130, in Series.__getitem__(self, key)
1127 return self._values[key]
1129 elif key_is_scalar:
-> 1130 return self._get_value(key)
1132 # Convert generator to list before going through hashable part
1133 # (We will iterate through the generator there to check for slices)
1134 if is_iterator(key):
File ~/work/pandas/pandas/pandas/core/series.py:1246, in Series._get_value(self, label, takeable)
1243 return self._values[label]
1245 # Similar to Index.get_value, but we do not fall back to positional
-> 1246 loc = self.index.get_loc(label)
1248 if is_integer(loc):
1249 return self._values[loc]
File ~/work/pandas/pandas/pandas/core/indexes/base.py:3819, in Index.get_loc(self, key)
3814 if isinstance(casted_key, slice) or (
3815 isinstance(casted_key, abc.Iterable)
3816 and any(isinstance(x, slice) for x in casted_key)
3817 ):
3818 raise InvalidIndexError(key)
-> 3819 raise KeyError(key) from err
3820 except TypeError:
3821 # If we have a listlike key, _check_indexing_error will raise
3822 # InvalidIndexError. Otherwise we fall through and re-raise
3823 # the TypeError.
3824 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
可以表示为
一种掩码数组解决方案:一个数据数组和一个布尔值数组,指示值是否存在或缺失。
使用一个特殊的哨兵值、位模式或一组哨兵值来表示各种 dtype 的
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 进行归一化,测量的是样本方差。请注意,pandas 和 NumPy 中的 cov()
都通过 N-1
进行归一化。
线程安全#
pandas 并非 100% 线程安全。已知问题与 copy()
方法有关。如果你在线程间共享的 DataFrame
对象上进行大量复制操作,我们建议在发生数据复制的线程内部持有锁。
更多信息请参见此链接。
字节序问题#
有时你可能需要处理在不同字节序机器上创建的数据,而不是你运行 Python 的机器。一个常见症状是出现以下错误
Traceback
...
ValueError: Big-endian buffer not supported on little-endian compiler
要解决此问题,你应该在将其传递给 Series
或 DataFrame
构造函数之前,将底层 NumPy 数组转换为本机系统字节序,方法类似于以下内容
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 字节序文档。