Pandas DataFrame

python中DataFrame对象 DataFrame是Pandas库中的一种数据结构,它是由多种类型的列组成的二维表数据结构,类似于Excel、SQL或Series对象构成的字典。DataFrame是最常用的Pandas对象,它与Series对象一样支持多种类型的数据。 阅读详情

http://pandas.pydata.org/pandas-docs/stable/api.html#dataframe

构造函数

方法描述
DataFrame([data, index, columns, dtype, copy])构造数据框

属性和数据

方法描述
Axesindex: row labels;columns: column labels
DataFrame.as_matrix([columns])转换为矩阵
DataFrame.dtypes返回数据的类型
DataFrame.ftypesReturn the ftypes (indication of sparse/dense and dtype) in this object.
DataFrame.get_dtype_counts()返回数据框数据类型的个数
DataFrame.get_ftype_counts()Return the counts of ftypes in this object.
DataFrame.select_dtypes([include, exclude])根据数据类型选取子数据框
DataFrame.valuesNumpy的展示方式
DataFrame.axes返回横纵坐标的标签名
DataFrame.ndim返回数据框的纬度
DataFrame.size返回数据框元素的个数
DataFrame.shape返回数据框的形状
DataFrame.memory_usage([index, deep])Memory usage of DataFrame columns.

类型转换

方法描述
DataFrame.astype(dtype[, copy, errors])转换数据类型
DataFrame.copy([deep])复制数据框
DataFrame.isnull()以布尔的方式返回空值
DataFrame.notnull()以布尔的方式返回非空值

索引和迭代

方法描述
DataFrame.head([n])返回前n行数据
DataFrame.at快速标签常量访问器
DataFrame.iat快速整型常量访问器
DataFrame.loc标签定位
DataFrame.iloc整型定位
DataFrame.insert(loc, column, value[, …])在特殊地点插入行
DataFrame.iter()Iterate over infor axis
DataFrame.iteritems()返回列名和序列的迭代器
DataFrame.iterrows()返回索引和序列的迭代器
DataFrame.itertuples([index, name])Iterate over DataFrame rows as namedtuples, with index value as first element of the tuple.
DataFrame.lookup(row_labels, col_labels)Label-based “fancy indexing” function for DataFrame.
DataFrame.pop(item)返回删除的项目
DataFrame.tail([n])返回最后n行
DataFrame.xs(key[, axis, level, drop_level])Returns a cross-section (row(s) or column(s)) from the Series/DataFrame.
DataFrame.isin(values)是否包含数据框中的元素
DataFrame.where(cond[, other, inplace, …])条件筛选
DataFrame.mask(cond[, other, inplace, axis, …])Return an object of same shape as self and whose corresponding entries are from self where cond is False and otherwise are from other.
DataFrame.query(expr[, inplace])Query the columns of a frame with a boolean expression.

二元运算

方法描述
DataFrame.add(other[, axis, level, fill_value])加法,元素指向
DataFrame.sub(other[, axis, level, fill_value])减法,元素指向
DataFrame.mul(other[, axis, level, fill_value])乘法,元素指向
DataFrame.div(other[, axis, level, fill_value])小数除法,元素指向
DataFrame.truediv(other[, axis, level, …])真除法,元素指向
DataFrame.floordiv(other[, axis, level, …])向下取整除法,元素指向
DataFrame.mod(other[, axis, level, fill_value])模运算,元素指向
DataFrame.pow(other[, axis, level, fill_value])幂运算,元素指向
DataFrame.radd(other[, axis, level, fill_value])右侧加法,元素指向
DataFrame.rsub(other[, axis, level, fill_value])右侧减法,元素指向
DataFrame.rmul(other[, axis, level, fill_value])右侧乘法,元素指向
DataFrame.rdiv(other[, axis, level, fill_value])右侧小数除法,元素指向
DataFrame.rtruediv(other[, axis, level, …])右侧真除法,元素指向
DataFrame.rfloordiv(other[, axis, level, …])右侧向下取整除法,元素指向
DataFrame.rmod(other[, axis, level, fill_value])右侧模运算,元素指向
DataFrame.rpow(other[, axis, level, fill_value])右侧幂运算,元素指向
DataFrame.lt(other[, axis, level])类似Array.lt
DataFrame.gt(other[, axis, level])类似Array.gt
DataFrame.le(other[, axis, level])类似Array.le
DataFrame.ge(other[, axis, level])类似Array.ge
DataFrame.ne(other[, axis, level])类似Array.ne
DataFrame.eq(other[, axis, level])类似Array.eq
DataFrame.combine(other, func[, fill_value, …])Add two DataFrame objects and do not propagate NaN values, so if for a
DataFrame.combine_first(other)Combine two DataFrame objects and default to non-null values in frame calling the method.

函数应用&分组&窗口

方法描述
DataFrame.apply(func[, axis, broadcast, …])应用函数
DataFrame.applymap(func)Apply a function to a DataFrame that is intended to operate elementwise, i.e.
DataFrame.aggregate(func[, axis])Aggregate using callable, string, dict, or list of string/callables
DataFrame.transform(func, *args, **kwargs)Call function producing a like-indexed NDFrame
DataFrame.groupby([by, axis, level, …])分组
DataFrame.rolling(window[, min_periods, …])滚动窗口
DataFrame.expanding([min_periods, freq, …])拓展窗口
DataFrame.ewm([com, span, halflife, alpha, …])指数权重窗口

描述统计学

方法描述
DataFrame.abs()返回绝对值
DataFrame.all([axis, bool_only, skipna, level])Return whether all elements are True over requested axis
DataFrame.any([axis, bool_only, skipna, level])Return whether any element is True over requested axis
DataFrame.clip([lower, upper, axis])Trim values at input threshold(s).
DataFrame.clip_lower(threshold[, axis])Return copy of the input with values below given value(s) truncated.
DataFrame.clip_upper(threshold[, axis])Return copy of input with values above given value(s) truncated.
DataFrame.corr([method, min_periods])返回本数据框成对列的相关性系数
DataFrame.corrwith(other[, axis, drop])返回不同数据框的相关性
DataFrame.count([axis, level, numeric_only])返回非空元素的个数
DataFrame.cov([min_periods])计算协方差
DataFrame.cummax([axis, skipna])Return cumulative max over requested axis.
DataFrame.cummin([axis, skipna])Return cumulative minimum over requested axis.
DataFrame.cumprod([axis, skipna])返回累积
DataFrame.cumsum([axis, skipna])返回累和
DataFrame.describe([percentiles, include, …])整体描述数据框
DataFrame.diff([periods, axis])1st discrete difference of object
DataFrame.eval(expr[, inplace])Evaluate an expression in the context of the calling DataFrame instance.
DataFrame.kurt([axis, skipna, level, …])返回无偏峰度Fisher’s (kurtosis of normal == 0.0).
DataFrame.mad([axis, skipna, level])返回偏差
DataFrame.max([axis, skipna, level, …])返回最大值
DataFrame.mean([axis, skipna, level, …])返回均值
DataFrame.median([axis, skipna, level, …])返回中位数
DataFrame.min([axis, skipna, level, …])返回最小值
DataFrame.mode([axis, numeric_only])返回众数
DataFrame.pct_change([periods, fill_method, …])返回百分比变化
DataFrame.prod([axis, skipna, level, …])返回连乘积
DataFrame.quantile([q, axis, numeric_only, …])返回分位数
DataFrame.rank([axis, method, numeric_only, …])返回数字的排序
DataFrame.round([decimals])Round a DataFrame to a variable number of decimal places.
DataFrame.sem([axis, skipna, level, ddof, …])返回无偏标准误
DataFrame.skew([axis, skipna, level, …])返回无偏偏度
DataFrame.sum([axis, skipna, level, …])求和
DataFrame.std([axis, skipna, level, ddof, …])返回标准误差
DataFrame.var([axis, skipna, level, ddof, …])返回无偏误差

从新索引&选取&标签操作

方法描述
DataFrame.add_prefix(prefix)添加前缀
DataFrame.add_suffix(suffix)添加后缀
DataFrame.align(other[, join, axis, level, …])Align two object on their axes with the
DataFrame.drop(labels[, axis, level, …])返回删除的列
DataFrame.drop_duplicates([subset, keep, …])Return DataFrame with duplicate rows removed, optionally only
DataFrame.duplicated([subset, keep])Return boolean Series denoting duplicate rows, optionally only
DataFrame.equals(other)两个数据框是否相同
DataFrame.filter([items, like, regex, axis])过滤特定的子数据框
DataFrame.first(offset)Convenience method for subsetting initial periods of time series data based on a date offset.
DataFrame.head([n])返回前n行
DataFrame.idxmax([axis, skipna])Return index of first occurrence of maximum over requested axis.
DataFrame.idxmin([axis, skipna])Return index of first occurrence of minimum over requested axis.
DataFrame.last(offset)Convenience method for subsetting final periods of time series data based on a date offset.
DataFrame.reindex([index, columns])Conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index.
DataFrame.reindex_axis(labels[, axis, …])Conform input object to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index.
DataFrame.reindex_like(other[, method, …])Return an object with matching indices to myself.
DataFrame.rename([index, columns])Alter axes input function or functions.
DataFrame.rename_axis(mapper[, axis, copy, …])Alter index and / or columns using input function or functions.
DataFrame.reset_index([level, drop, …])For DataFrame with multi-level index, return new DataFrame with labeling information in the columns under the index names, defaulting to ‘level_0’, ‘level_1’, etc.
DataFrame.sample([n, frac, replace, …])返回随机抽样
DataFrame.select(crit[, axis])Return data corresponding to axis labels matching criteria
DataFrame.set_index(keys[, drop, append, …])Set the DataFrame index (row labels) using one or more existing columns.
DataFrame.tail([n])返回最后几行
DataFrame.take(indices[, axis, convert, is_copy])Analogous to ndarray.take
DataFrame.truncate([before, after, axis, copy])Truncates a sorted NDFrame before and/or after some particular index value.

处理缺失值

方法描述
DataFrame.dropna([axis, how, thresh, …])Return object with labels on given axis omitted where alternately any
DataFrame.fillna([value, method, axis, …])填充空值
DataFrame.replace([to_replace, value, …])Replace values given in ‘to_replace’ with ‘value’.

从新定型&排序&转变形态

方法描述
DataFrame.pivot([index, columns, values])Reshape data (produce a “pivot” table) based on column values.
DataFrame.reorder_levels(order[, axis])Rearrange index levels using input order.
DataFrame.sort_values(by[, axis, ascending, …])Sort by the values along either axis
DataFrame.sort_index([axis, level, …])Sort object by labels (along an axis)
DataFrame.nlargest(n, columns[, keep])Get the rows of a DataFrame sorted by the n largest values of columns.
DataFrame.nsmallest(n, columns[, keep])Get the rows of a DataFrame sorted by the n smallest values of columns.
DataFrame.swaplevel([i, j, axis])Swap levels i and j in a MultiIndex on a particular axis
DataFrame.stack([level, dropna])Pivot a level of the (possibly hierarchical) column labels, returning a DataFrame (or Series in the case of an object with a single level of column labels) having a hierarchical index with a new inner-most level of row labels.
DataFrame.unstack([level, fill_value])Pivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels.
DataFrame.melt([id_vars, value_vars, …])“Unpivots” a DataFrame from wide format to long format, optionally
DataFrame.TTranspose index and columns
DataFrame.to_panel()Transform long (stacked) format (DataFrame) into wide (3D, Panel) format.
DataFrame.to_xarray()Return an xarray object from the pandas object.
DataFrame.transpose(*args, **kwargs)Transpose index and columns

Combining& joining&merging

方法描述
DataFrame.append(other[, ignore_index, …])追加数据
DataFrame.assign(**kwargs)Assign new columns to a DataFrame, returning a new object (a copy) with all the original columns in addition to the new ones.
DataFrame.join(other[, on, how, lsuffix, …])Join columns with other DataFrame either on index or on a key column.
DataFrame.merge(right[, how, on, left_on, …])Merge DataFrame objects by performing a database-style join operation by columns or indexes.
DataFrame.update(other[, join, overwrite, …])Modify DataFrame in place using non-NA values from passed DataFrame.

时间序列

方法描述
DataFrame.asfreq(freq[, method, how, …])将时间序列转换为特定的频次
DataFrame.asof(where[, subset])The last row without any NaN is taken (or the last row without
DataFrame.shift([periods, freq, axis])Shift index by desired number of periods with an optional time freq
DataFrame.first_valid_index()Return label for first non-NA/null value
DataFrame.last_valid_index()Return label for last non-NA/null value
DataFrame.resample(rule[, how, axis, …])Convenience method for frequency conversion and resampling of time series.
DataFrame.to_period([freq, axis, copy])Convert DataFrame from DatetimeIndex to PeriodIndex with desired
DataFrame.to_timestamp([freq, how, axis, copy])Cast to DatetimeIndex of timestamps, at beginning of period
DataFrame.tz_convert(tz[, axis, level, copy])Convert tz-aware axis to target time zone.
DataFrame.tz_localize(tz[, axis, level, …])Localize tz-naive TimeSeries to target time zone.

作图

方法描述
DataFrame.plot([x, y, kind, ax, ….])DataFrame plotting accessor and method
DataFrame.plot.area([x, y])面积图Area plot
DataFrame.plot.bar([x, y])垂直条形图Vertical bar plot
DataFrame.plot.barh([x, y])水平条形图Horizontal bar plot
DataFrame.plot.box([by])箱图Boxplot
DataFrame.plot.density(**kwds)核密度Kernel Density Estimate plot
DataFrame.plot.hexbin(x, y[, C, …])Hexbin plot
DataFrame.plot.hist([by, bins])直方图Histogram
DataFrame.plot.kde(**kwds)核密度Kernel Density Estimate plot
DataFrame.plot.line([x, y])线图Line plot
DataFrame.plot.pie([y])饼图Pie chart
DataFrame.plot.scatter(x, y[, s, c])散点图Scatter plot
DataFrame.boxplot([column, by, ax, …])Make a box plot from DataFrame column optionally grouped by some columns or
DataFrame.hist(data[, column, by, grid, …])Draw histogram of the DataFrame’s series using matplotlib / pylab.

转换为其他格式

方法描述
DataFrame.from_csv(path[, header, sep, …])Read CSV file (DEPRECATED, please use pandas.read_csv() instead).
DataFrame.from_dict(data[, orient, dtype])Construct DataFrame from dict of array-like or dicts
DataFrame.from_items(items[, columns, orient])Convert (key, value) pairs to DataFrame.
DataFrame.from_records(data[, index, …])Convert structured or record ndarray to DataFrame
DataFrame.info([verbose, buf, max_cols, …])Concise summary of a DataFrame.
DataFrame.to_pickle(path[, compression, …])Pickle (serialize) object to input file path.
DataFrame.to_csv([path_or_buf, sep, na_rep, …])Write DataFrame to a comma-separated values (csv) file
DataFrame.to_hdf(path_or_buf, key, **kwargs)Write the contained data to an HDF5 file using HDFStore.
DataFrame.to_sql(name, con[, flavor, …])Write records stored in a DataFrame to a SQL database.
DataFrame.to_dict([orient, into])Convert DataFrame to dictionary.
DataFrame.to_excel(excel_writer[, …])Write DataFrame to an excel sheet
DataFrame.to_json([path_or_buf, orient, …])Convert the object to a JSON string.
DataFrame.to_html([buf, columns, col_space, …])Render a DataFrame as an HTML table.
DataFrame.to_feather(fname)write out the binary feather-format for DataFrames
DataFrame.to_latex([buf, columns, …])Render an object to a tabular environment table.
DataFrame.to_stata(fname[, convert_dates, …])A class for writing Stata binary dta files from array-like objects
DataFrame.to_msgpack([path_or_buf, encoding])msgpack (serialize) object to input file path
DataFrame.to_gbq(destination_table, project_id)Write a DataFrame to a Google BigQuery table.
DataFrame.to_records([index, convert_datetime64])Convert DataFrame to record array.
DataFrame.to_sparse([fill_value, kind])Convert to SparseDataFrame
DataFrame.to_dense()Return dense representation of NDFrame (as opposed to sparse)
DataFrame.to_string([buf, columns, …])Render a DataFrame to a console-friendly tabular output.
DataFrame.to_clipboard([excel, sep])Attempt to write text representation of object to the system clipboard This can be pasted into Excel, for example.
Spark中DataFrame与Pandas中DataFrame的区别 目录 为何使用 PySpark DataFrame Pandas DataFrame 数据结构特性 Spark DataFrame 数据结构与存储特性 使用 Spark DataFrame 优势 Spark toPandas 详解 Spark与Pandas中的DataFrame的区别 为何使用 PySpark DataFrame 使用 pandas 进行数据处理,dataframe... 阅读详情

相关推荐

【Pandas】pandas DataFrame boxplot

`pandas.DataFrame.boxplot()` 是用于绘制 **箱型图(Boxplot)** 的方法,它是对 `matplotlib.pyplot.boxplot()` 的封装,专为 DataFrame 设计,支持多列数据的批量可视化。

weixin_39648905的博客 1931

[pandas] 详解pandas库的pd.merge函数

本篇详细说明merge的应用,join 和concatenate的拼接方法的与之相似。 pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True, suffixe...

ande6905的博客 1233

【Pandas】pandas DataFrame T

`pandas.DataFrame.T` 是一个**属性(不是方法)**,用于**转置 DataFrame**,即将行和列互换。它是 `DataFrame.transpose()` 的快捷方式,常用于数据重塑、可视化或机器学习任务中调整数据结构。

weixin_39648905的博客 1596

Python的DataFrame

在数据分析中,数据框架(DataFrame)是一个强大的工具。它能够让我们以一种结构化的方式来处理和分析数据。Python中的Pandas库为我们提供了这种数据结构。本文将带你从零开始,逐步深入了解DataFrame的各个方面,通过实际代码来展示其应用。点击进入官方文档DataFrame是Pandas库中的一个核心数据结构,它是一个二维标签化的数据结构,可以认为它是一个Excel表格或者SQL表,具有行标签和列标签。通过本文,我们了解了什么是DataFrame,如何创建它,以及一些基础和进阶的操作。

qq_74538234的博客 9859

【Pandas】pandas DataFrame hist

`pandas.DataFrame.hist()` 是用于绘制 **直方图(Histogram)** 的方法,可以对 DataFrame 中的一列或多列数据进行频数分布可视化。 该方法是对 `matplotlib.pyplot.hist()` 的封装,支持分组绘图、子图布局、样式定制等功能。

weixin_39648905的博客 1580

【Pandas】pandas DataFrame update

`pandas.DataFrame.update()` 是一个用于**就地(in-place)更新 DataFrame 中数据**的方法。它会根据另一个 DataFrame 或 Series 的值来更新当前 DataFrame 中的对应位置数据。 默认情况下,它不会修改原始 DataFrame 的形状(即不新增列),只更新交集部分的数据。

weixin_39648905的博客 1372

Python数据处理DataFrame小记

python数据处理小记简介:1、DataFram定义:2、DataFrame的append3、DataFrame去除列或行 简介: 目前从事数据版块的工作,基本就是数仓、ETL、BI这一块。学习了一个python机器学习课程,在此记下学习过程中遇到的坑。 1、DataFram定义: 只定义列名 import pandas as pd df = pd.DataFrame(columns=['姓名...

不会编程的汪 4万+

【Pandas】pandas DataFrame to_excel

`pandas.DataFrame.to_excel()` 是 Pandas 提供的用于将 DataFrame 写入 Excel 文件的方法。它支持多种参数来控制输出格式、位置、缺失值表示等,适用于生成结构化报表或数据导出。

weixin_39648905的博客 1930

python学习--DataFrame

目录 一、DataFrame对象的创建 1、根据列表创建: 情况1:由二维列表 情况2:由元组tuple组成的列表 情况3:由字典dict组成的列表 情况4:由数组array组成的列表 情况5:由序列series组成的列表 2、根据字典创建: 情况1:由元组tuple组成的字典 情况2:由列表list组成的字典 情况3:由字典dict组成的字典 情况4:由数组array组成的字典 情况5:由序列series组成的字典 情况6:由复合式的字典 3、根据二维数组ndarray创

m0_60392490的博客 3万+

【Pandas】pandas DataFrame tail

`pandas.DataFrame.tail(n=5)` 是一个用于**快速查看 DataFrame 最后几行数据**的方法。它默认返回最后 5 行,常用于数据探索、调试和快速检查数据集的末尾内容。

weixin_39648905的博客 1362

【Pandas】pandas DataFrame merge

`pandas.DataFrame.merge()` 是 Pandas 中用于**基于一个或多个键将两个 DataFrame 进行数据库风格的合并(join)**的方法。它类似于 SQL 中的 JOIN 操作,支持多种连接方式(如 `inner`, `left`, `right`, `outer`),并可以指定左右 DataFrame 的连接键。

weixin_39648905的博客 1188

【Pandas】pandas DataFrame resample

`pandas.DataFrame.resample()` 是 Pandas 中用于**对时间序列数据进行重采样(resampling)**的核心方法。它类似于 SQL 中的“GROUP BY 时间窗口”操作,常用于将高频时间序列数据聚合为低频(如从分钟级到小时级、日级等),也支持升采样(插值填充)。

weixin_39648905的博客 1118

【Pandas】pandas DataFrame melt

`pandas.DataFrame.melt()` 是一个用于**将 DataFrame 从宽格式转换为长格式(“融化”操作)**的方法。它常用于数据重塑,特别是当你希望将多个列的值合并到一个列中,并保留某些标识变量(如 ID、类别等)。 它是 `pivot()` 的反向操作,非常适合用于后续的数据分析或可视化任务。

weixin_39648905的博客 1074

【Pandas】pandas DataFrame squeeze

`pandas.DataFrame.squeeze()` 是一个用于**将长度为 1 的轴(axis)从 DataFrame 中“挤压”掉,返回更简洁的数据结构(如 Series)**的方法。 它是 Pandas 中用于数据维度压缩的重要工具之一,尤其适用于当你确定某些维度只有一个元素时,可以将其转换为更易处理的格式。

weixin_39648905的博客 891

【Pandas】pandas DataFrame shape

`pandas.DataFrame.shape` 是一个属性,用于返回 DataFrame 的维度信息,即行数和列数。`shape` 属性返回一个包含两个整数的元组,第一个整数表示行数,第二个整数表示列数。

weixin_39648905的博客 1475

【Pandas】pandas DataFrame mask

`pandas.DataFrame.mask(cond, other=<no_default>, *, inplace=False, axis=None, level=None)` 方法用于根据条件筛选 DataFrame 中的元素。如果条件为 `True`,则用 `other` 参数指定的值替换该元素;如果条件为 `False`,则保留原值。

weixin_39648905的博客 1110

【Pandas】pandas DataFrame dtypes

`pandas.DataFrame.dtypes` 属性用于获取 DataFrame 中每一列的数据类型。通过 `dtypes` 属性,可以查看 DataFrame 中各列的数据类型,这对于数据验证和处理非常重要。

weixin_39648905的博客 1305

【Pandas】pandas DataFrame cumsum

`pandas.DataFrame.cumsum()` 方法用于计算 DataFrame 中每列或每行的**累计和(cumulative sum)**。该方法返回一个与原 DataFrame 形状相同的对象,每个位置上的值是到该位置为止所有元素的累加和。

weixin_39648905的博客 1179
上一篇: Pandas Index 属性
下一篇: Pandas Series
Claroja
博客等级 码龄11年 1396粉丝 2709原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值