pandas.DataFrame#
- class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)[源代码]#
二维的、可变大小的、可能异构的表格数据。
数据结构还包含带标签的轴(行和列)。算术运算会根据行和列标签进行对齐。可以将其视为 Series 对象的类字典容器。主要的 pandas 数据结构。
- Parameters:
- datandarray(结构化或同质)、可迭代对象、dict 或 DataFrame
Dict 可以包含 Series、数组、常量、dataclass 或类似列表的对象。如果 data 是 dict,则列顺序遵循插入顺序。如果 dict 包含具有已定义索引的 Series,则会根据其索引进行对齐。当 data 本身是 Series 或 DataFrame 时,也会发生对齐。对 Series/DataFrame 输入进行对齐。
如果 data 是字典列表,则列顺序遵循插入顺序。
- indexIndex 或类数组
用于结果帧的索引。如果输入数据中没有索引信息且未提供索引,则默认为 RangeIndex。
- columnsIndex 或类数组
当数据没有列标签时,用于结果帧的列标签,默认为 RangeIndex(0, 1, 2, …, n)。如果数据包含列标签,则执行列选择。
- dtypedtype,default None
要强制设置的数据类型。只允许一个 dtype。如果为 None,则推断。
- copybool 或 None,default None
从输入中复制数据。对于 dict 数据,默认值 None 的行为类似于
copy=True。对于 DataFrame 或 2D ndarray 输入,默认值 None 的行为类似于copy=False。如果数据是包含一个或多个 Series(可能dtypes不同)的 dict,则copy=False将确保这些输入不被复制。在 1.3.0 版本发生变更.
参见
DataFrame.from_records从元组(也包括记录数组)构造。
DataFrame.from_dict从 Series、数组或字典的字典构造。
read_csv将逗号分隔值 (csv) 文件读取到 DataFrame 中。
read_table将通用分隔文件读取到 DataFrame 中。
read_clipboard将剪贴板中的文本读取到 DataFrame 中。
Notes
请参考 User Guide 获取更多信息。
Examples
从字典构造 DataFrame。
>>> d = {'col1': [1, 2], 'col2': [3, 4]} >>> df = pd.DataFrame(data=d) >>> df col1 col2 0 1 3 1 2 4
请注意,推断出的 dtype 是 int64。
>>> df.dtypes col1 int64 col2 int64 dtype: object
强制设置单个 dtype:
>>> df = pd.DataFrame(data=d, dtype=np.int8) >>> df.dtypes col1 int8 col2 int8 dtype: object
从包含 Series 的字典构造 DataFrame:
>>> d = {'col1': [0, 1, 2, 3], 'col2': pd.Series([2, 3], index=[2, 3])} >>> pd.DataFrame(data=d, index=[0, 1, 2, 3]) col1 col2 0 0 NaN 1 1 NaN 2 2 2.0 3 3 3.0
从 numpy ndarray 构造 DataFrame:
>>> df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), ... columns=['a', 'b', 'c']) >>> df2 a b c 0 1 2 3 1 4 5 6 2 7 8 9
从具有已标记列的 numpy ndarray 构造 DataFrame:
>>> data = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], ... dtype=[("a", "i4"), ("b", "i4"), ("c", "i4")]) >>> df3 = pd.DataFrame(data, columns=['c', 'a']) ... >>> df3 c a 0 3 1 1 6 4 2 9 7
从 dataclass 构造 DataFrame:
>>> from dataclasses import make_dataclass >>> Point = make_dataclass("Point", [("x", int), ("y", int)]) >>> pd.DataFrame([Point(0, 0), Point(0, 3), Point(2, 3)]) x y 0 0 0 1 0 3 2 2 3
从 Series/DataFrame 构造:
>>> ser = pd.Series([1, 2, 3], index=["a", "b", "c"]) >>> df = pd.DataFrame(data=ser, index=["a", "c"]) >>> df 0 a 1 c 3
>>> df1 = pd.DataFrame([1, 2, 3], index=["a", "b", "c"], columns=["x"]) >>> df2 = pd.DataFrame(data=df1, index=["a", "c"]) >>> df2 x a 1 c 3
Attributes
DataFrame 的转置。
按行/列标签对访问单个值。
此数据集的全局属性字典。
返回表示 DataFrame 轴的列表。
DataFrame 的列标签。
返回 DataFrame 中的 dtypes。
指示 Series/DataFrame 是否为空。
flags获取与此 pandas 对象关联的属性。
按整数位置的行/列对访问单个值。
(已弃用) 纯粹基于整数位置的索引,用于按位置选择。
DataFrame 的索引(行标签)。
通过标签或布尔数组访问一组行和列。
返回一个整数,表示轴/数组的维度数。
返回一个元组,表示 DataFrame 的维度。
返回一个整数,表示此对象中的元素数量。
返回一个 Styler 对象。
返回 DataFrame 的 Numpy 表示。
Methods
abs()返回一个 Series/DataFrame,其中包含每个元素的绝对数值。
add(other[, axis, level, fill_value])获取 DataFrame 和 other 的逐元素加法(二元运算符 add)。
add_prefix(prefix[, axis])在标签前添加字符串 prefix。
add_suffix(suffix[, axis])在标签后添加字符串 suffix。
agg([func, axis])沿指定轴使用一个或多个操作进行聚合。
aggregate([func, axis])沿指定轴使用一个或多个操作进行聚合。
align(other[, join, axis, level, copy, ...])使用指定的连接方法按轴对齐两个对象。
all([axis, bool_only, skipna])返回所有元素是否为 True,可能沿轴进行。
any(*[, axis, bool_only, skipna])返回是否有任何元素是 True,可能沿轴进行。
apply(func[, axis, raw, result_type, args, ...])沿 DataFrame 的轴应用函数。
applymap(func[, na_action])(已弃用) 逐元素应用函数到 DataFrame。
asfreq(freq[, method, how, normalize, ...])将时间序列转换为指定频率。
asof(where[, subset])返回 where 之前最后一个不含 NaN 的行(或行)。
assign(**kwargs)为 DataFrame 分配新列。
astype(dtype[, copy, errors])将 pandas 对象转换为指定的 dtype
dtype。at_time(time[, asof, axis])选择一天中特定时间的(例如,上午 9:30)值。
backfill(*[, axis, inplace, limit, downcast])(已弃用) 使用下一个有效观测值填充 NaN/NA 值以填补间隙。
between_time(start_time, end_time[, ...])选择一天中特定时间段内的(例如,上午 9:00-9:30)值。
bfill(*[, axis, inplace, limit, limit_area, ...])使用下一个有效观测值填充 NaN/NA 值以填补间隙。
bool()(已弃用) 返回单个元素的 Series 或 DataFrame 的布尔值。
boxplot([column, by, ax, fontsize, rot, ...])从 DataFrame 列制作箱线图。
clip([lower, upper, axis, inplace])在输入阈值处截断值。
combine(other, func[, fill_value, overwrite])将另一 DataFrame 进行逐列合并。
combine_first(other)使用 other 中相同位置的值更新 null 元素。
compare(other[, align_axis, keep_shape, ...])比较另一个 DataFrame 并显示差异。
convert_dtypes([infer_objects, ...])使用支持
pd.NA的 dtype 将列转换为最佳可能的 dtype。copy([deep])复制此对象的索引和数据。
corr([method, min_periods, numeric_only])计算列的成对相关性,排除 NA/null 值。
corrwith(other[, axis, drop, method, ...])计算成对相关性。
count([axis, numeric_only])计算每列或每行的非 NA 单元格数。
cov([min_periods, ddof, numeric_only])计算列的成对协方差,排除 NA/null 值。
cummax([axis, skipna])返回 DataFrame 或 Series 轴上的累积最大值。
cummin([axis, skipna])返回 DataFrame 或 Series 轴上的累积最小值。
cumprod([axis, skipna])返回 DataFrame 或 Series 轴上的累积乘积。
cumsum([axis, skipna])返回 DataFrame 或 Series 轴上的累积和。
describe([percentiles, include, exclude])生成描述性统计信息。
diff([periods, axis])元素的离散差分。
div(other[, axis, level, fill_value])对 DataFrame 和 other 进行浮点除法,逐元素进行(二元运算符 truediv)。
divide(other[, axis, level, fill_value])对 DataFrame 和 other 进行浮点除法,逐元素进行(二元运算符 truediv)。
dot(other)计算 DataFrame 和 other 之间的矩阵乘积。
drop([labels, axis, index, columns, level, ...])删除行或列中指定的标签。
drop_duplicates([subset, keep, inplace, ...])返回删除重复行后的 DataFrame。
droplevel(level[, axis])返回删除所请求的索引/列级别的 Series/DataFrame。
dropna(*[, axis, how, thresh, subset, ...])删除缺失值。
duplicated([subset, keep])返回表示重复行的布尔 Series。
eq(other[, axis, level])获取 DataFrame 和 other 的相等值,逐元素进行(二元运算符 eq)。
equals(other)测试两个对象是否包含相同元素。
eval(expr, *[, inplace])计算描述 DataFrame 列操作的字符串。
ewm([com, span, halflife, alpha, ...])提供指数加权 (EW) 计算。
expanding([min_periods, axis, method])提供扩展窗口计算。
explode(column[, ignore_index])将类列表的每个元素转换为一行,并复制索引值。
ffill(*[, axis, inplace, limit, limit_area, ...])使用最后一个有效观测值传播NA/NaN值。
fillna([value, method, axis, inplace, ...])使用指定的方法填充NA/NaN值。
filter([items, like, regex, axis])根据指定的索引标签对DataFrame的行或列进行子集选择。
first(offset)(已弃用) 根据日期偏移量选择时间序列数据的初始时段。
返回第一个非NA值的索引,如果找不到非NA值,则返回None。
floordiv(other[, axis, level, fill_value])对DataFrame和其他值进行整除,逐元素进行(二元运算符 floordiv)。
from_dict(data[, orient, dtype, columns])从数组类或字典的字典构建DataFrame。
from_records(data[, index, exclude, ...])将结构化或记录式ndarray转换为DataFrame。
ge(other[, axis, level])对DataFrame和其他值进行大于或等于比较,逐元素进行(二元运算符 ge)。
get(key[, default])获取给定键的对象项(例如:DataFrame列)。
groupby([by, axis, level, as_index, sort, ...])使用映射器或列Series对DataFrame进行分组。
gt(other[, axis, level])对DataFrame和其他值进行大于比较,逐元素进行(二元运算符 gt)。
head([n])返回前`n`行。
hist([column, by, grid, xlabelsize, xrot, ...])绘制DataFrame列的直方图。
idxmax([axis, skipna, numeric_only])返回请求轴上最大值的第一个出现索引。
idxmin([axis, skipna, numeric_only])返回请求轴上最小值第一个出现的索引。
infer_objects([copy])尝试为对象列推断更好的数据类型(dtypes)。
info([verbose, buf, max_cols, memory_usage, ...])打印DataFrame的简洁摘要。
insert(loc, column, value[, allow_duplicates])在指定位置将列插入DataFrame。
interpolate([method, axis, limit, inplace, ...])使用插值方法填充NaN值。
isetitem(loc, value)在位置`loc`的列中设置给定值。
isin(values)DataFrame中的每个元素是否包含在values中。
isna()检测缺失值。
isnull()DataFrame.isnull 是 DataFrame.isna 的别名。
items()迭代(列名,Series)对。
iterrows()迭代DataFrame行作为(索引,Series)对。
itertuples([index, name])将DataFrame行迭代为命名元组。
join(other[, on, how, lsuffix, rsuffix, ...])连接另一个DataFrame的列。
keys()获取“info axis”(参见索引章节更多内容)。
kurt([axis, skipna, numeric_only])返回所请求轴上的无偏峰度。
kurtosis([axis, skipna, numeric_only])返回所请求轴上的无偏峰度。
last(offset)(已弃用) 根据日期偏移量选择时间序列数据的最后时段。
返回最后一个非NA值的索引,如果找不到非NA值,则返回None。
le(other[, axis, level])获取 DataFrame 和 other 小于或等于的元素(二进制运算符 le)。
lt(other[, axis, level])获取 DataFrame 和 other 小于的元素(二进制运算符 lt)。
map(func[, na_action])将函数逐个元素应用到 DataFrame。
mask(cond[, other, inplace, axis, level])在条件为 True 的位置替换值。
max([axis, skipna, numeric_only])返回请求轴上值的最大值。
mean([axis, skipna, numeric_only])返回请求轴上值的平均值。
median([axis, skipna, numeric_only])返回请求轴上值的中位数。
melt([id_vars, value_vars, var_name, ...])将 DataFrame 从宽格式重塑为长格式,并可选择保留标识符。
memory_usage([index, deep])返回每列的内存使用量(以字节为单位)。
merge(right[, how, on, left_on, right_on, ...])将 DataFrame 或命名 Series 对象与数据库风格的连接(join)进行合并。
min([axis, skipna, numeric_only])返回请求轴上值的最小值。
mod(other[, axis, level, fill_value])获取 DataFrame 和 other 的模(remainder),逐个元素计算(二进制运算符 mod)。
mode([axis, numeric_only, dropna])获取所选轴上每个元素的众数。
mul(other[, axis, level, fill_value])获取 DataFrame 和 other 的乘积,逐个元素计算(二进制运算符 mul)。
multiply(other[, axis, level, fill_value])获取 DataFrame 和 other 的乘积,逐个元素计算(二进制运算符 mul)。
ne(other[, axis, level])获取 DataFrame 和 other 不等于的元素(二进制运算符 ne)。
nlargest(n, columns[, keep])返回按 columns 降序排序的前 n 行。
notna()检测存在的(非缺失)值。
notnull()DataFrame.notnull 是 DataFrame.notna 的别名。
nsmallest(n, columns[, keep])返回按 columns 升序排序的前 n 行。
nunique([axis, dropna])计算指定轴上不同元素的数量。
pad(*[, axis, inplace, limit, downcast])(已弃用)通过传播最后一个有效观测值来填充 NA/NaN 值。
pct_change([periods, fill_method, limit, freq])当前元素与先前元素之间的分数变化。
pipe(func, *args, **kwargs)应用可链式调用的函数,这些函数期望 Series 或 DataFrame。
pivot(*, columns[, index, values])返回由给定的索引/列值组织的重塑后的 DataFrame。
pivot_table([values, index, columns, ...])创建电子表格风格的透视表作为 DataFrame。
pop(item)返回指定项并从 DataFrame 中删除。
pow(other[, axis, level, fill_value])获取 DataFrame 和 other 的指数幂,逐个元素计算(二进制运算符 pow)。
prod([axis, skipna, numeric_only, min_count])返回请求轴上值的乘积。
product([axis, skipna, numeric_only, min_count])返回请求轴上值的乘积。
quantile([q, axis, numeric_only, ...])在指定轴上指定分位数的返回值。
query(expr, *[, inplace])使用布尔表达式查询 DataFrame 列。
radd(other[, axis, level, fill_value])获取 DataFrame 和其他元素的加法,逐元素进行(二元运算符 radd)。
rank([axis, method, numeric_only, ...])沿指定轴计算数值数据的排名(1 到 n)。
rdiv(other[, axis, level, fill_value])获取 DataFrame 和其他元素的浮点数除法,逐元素进行(二元运算符 rtruediv)。
reindex([labels, index, columns, axis, ...])根据可选的填充逻辑调整 DataFrame 的索引。
reindex_like(other[, method, copy, limit, ...])返回具有与 other 对象匹配的索引的对象。
rename([mapper, index, columns, axis, copy, ...])重命名列或索引标签。
rename_axis([mapper, index, columns, axis, ...])设置索引或列的轴名称。
reorder_levels(order[, axis])使用输入的顺序重新排列索引级别。
replace([to_replace, value, inplace, limit, ...])用 value 替换 to_replace 中给定的值。
resample(rule[, axis, closed, label, ...])重采样时间序列数据。
reset_index([level, drop, inplace, ...])重置索引或其某个级别。
rfloordiv(other[, axis, level, fill_value])获取 DataFrame 和其他元素的整数除法,逐元素进行(二元运算符 rfloordiv)。
rmod(other[, axis, level, fill_value])获取 DataFrame 和其他元素的模运算,逐元素进行(二元运算符 rmod)。
rmul(other[, axis, level, fill_value])获取 DataFrame 和其他元素的乘法,逐元素进行(二元运算符 rmul)。
rolling(window[, min_periods, center, ...])提供滚动窗口计算。
round([decimals])将 DataFrame 四舍五入到可变小数位数。
rpow(other[, axis, level, fill_value])获取 DataFrame 和其他元素的指数幂,逐元素进行(二元运算符 rpow)。
rsub(other[, axis, level, fill_value])获取 DataFrame 和其他元素的减法,逐元素进行(二元运算符 rsub)。
rtruediv(other[, axis, level, fill_value])获取 DataFrame 和其他元素的浮点数除法,逐元素进行(二元运算符 rtruediv)。
sample([n, frac, replace, weights, ...])从对象的轴中返回随机样本。
select_dtypes([include, exclude])根据列的数据类型返回 DataFrame 列的子集。
sem([axis, skipna, ddof, numeric_only])在指定轴上返回无偏标准误差。
set_axis(labels, *[, axis, copy])为指定轴分配所需的索引。
set_flags(*[, copy, allows_duplicate_labels])返回一个具有更新标志的新对象。
set_index(keys, *[, drop, append, inplace, ...])使用现有列设置 DataFrame 索引。
shift([periods, freq, axis, fill_value, suffix])使用可选的时间 freq 将索引移动指定的周期数。
skew([axis, skipna, numeric_only])在指定轴上返回无偏偏度。
sort_index(*[, axis, level, ascending, ...])按标签(沿轴)对对象进行排序。
sort_values(by, *[, axis, ascending, ...])沿任一轴按值进行排序。
squeeze([axis])将一维轴对象压缩成标量。
stack([level, dropna, sort, future_stack])将指定级别的列堆叠到索引。
std([axis, skipna, ddof, numeric_only])返回所请求轴上的样本标准差。
sub(other[, axis, level, fill_value])DataFrame 与其他项的减法,逐元素(二元运算符 sub)。
subtract(other[, axis, level, fill_value])DataFrame 与其他项的减法,逐元素(二元运算符 sub)。
sum([axis, skipna, numeric_only, min_count])返回所请求轴上的值的总和。
swapaxes(axis1, axis2[, copy])(已弃用)交换轴并相应地交换值轴。
swaplevel([i, j, axis])交换
MultiIndex中的级别 i 和 j。tail([n])返回最后 n 行。
take(indices[, axis])沿轴返回给定 位置 索引中的元素。
to_clipboard(*[, excel, sep])将对象复制到系统剪贴板。
to_csv([path_or_buf, sep, na_rep, ...])将对象写入逗号分隔值(csv)文件。
to_dict([orient, into, index])将 DataFrame 转换为字典。
to_excel(excel_writer, *[, sheet_name, ...])将对象写入 Excel 工作表。
to_feather(path, **kwargs)将 DataFrame 写入二进制 Feather 格式。
to_gbq(destination_table, *[, project_id, ...])(已弃用)将 DataFrame 写入 Google BigQuery 表。
to_hdf(path_or_buf, *, key[, mode, ...])使用 HDFStore 将包含的数据写入 HDF5 文件。
to_html([buf, columns, col_space, header, ...])将 DataFrame 渲染为 HTML 表。
to_json([path_or_buf, orient, date_format, ...])将对象转换为 JSON 字符串。
to_latex([buf, columns, header, index, ...])将对象渲染为 LaTeX tabular、longtable 或嵌套表。
to_markdown([buf, mode, index, storage_options])以 Markdown 友好的格式打印 DataFrame。
to_numpy([dtype, copy, na_value])将 DataFrame 转换为 NumPy 数组。
to_orc([path, engine, index, engine_kwargs])将 DataFrame 写入 ORC 格式。
to_parquet([path, engine, compression, ...])将 DataFrame 写入二进制 parquet 格式。
to_period([freq, axis, copy])将 DataFrame 从 DatetimeIndex 转换为 PeriodIndex。
to_pickle(path, *[, compression, protocol, ...])将对象 Pickle(序列化)到文件。
to_records([index, column_dtypes, index_dtypes])将 DataFrame 转换为 NumPy 记录数组。
to_sql(name, con, *[, schema, if_exists, ...])将存储在 DataFrame 中的记录写入 SQL 数据库。
to_stata(path, *[, convert_dates, ...])将 DataFrame 对象导出为 Stata dta 格式。
to_string([buf, columns, col_space, header, ...])将 DataFrame 渲染成控制台友好的表格输出。
to_timestamp([freq, how, axis, copy])将DataFrame转换为时间戳的DatetimeIndex,位于周期*开始*处。
to_xarray()从pandas对象返回一个xarray对象。
to_xml([path_or_buffer, index, root_name, ...])将DataFrame渲染为XML文档。
transform(func[, axis])在self上调用``func``,生成一个与self具有相同轴形状的DataFrame。
transpose(*args[, copy])转置索引和列。
truediv(other[, axis, level, fill_value])对 DataFrame 和 other 进行浮点除法,逐元素进行(二元运算符 truediv)。
truncate([before, after, axis, copy])截断Series或DataFrame在某个索引值之前和之后的部分。
tz_convert(tz[, axis, level, copy])将时区感知的轴转换为目标时区。
tz_localize(tz[, axis, level, copy, ...])将Series或DataFrame的无时区索引本地化为目标时区。
unstack([level, fill_value, sort])对(必然是分层的)索引标签的某个级别进行“逆透视”。
update(other[, join, overwrite, ...])使用另一个DataFrame中的非NA值原地修改。
value_counts([subset, normalize, sort, ...])返回一个Series,其中包含DataFrame中每个不同行的频率。
var([axis, skipna, ddof, numeric_only])返回所请求轴上无偏方差。
where(cond[, other, inplace, axis, level])替换条件为False的值。
xs(key[, axis, level, drop_level])从Series/DataFrame中返回横截面。