pandas.DataFrame#

class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)[原始碼]#

二維的、大小可變的、可能異構的表格資料。

該資料結構也包含帶標籤的軸(行和列)。算術運算會在行和列標籤上對齊。可以看作是 Series 物件的類似 dict 的容器。主要的 pandas 資料結構。

引數:
datandarray (結構化或同質化), Iterable, dict, 或 DataFrame

字典可以包含 Series、陣列、常量、資料類或類列表物件。如果 data 是字典,則列順序遵循插入順序。如果字典包含有定義的索引的 Series,則會按其索引對齊。當 data 本身是 Series 或 DataFrame 時,也會發生這種對齊。對齊發生在 Series/DataFrame 輸入上。

如果 data 是字典列表,則列順序遵循插入順序。

indexIndex 或類陣列

用於結果 DataFrame 的索引。如果輸入資料中沒有索引資訊且未提供索引,則預設為 RangeIndex。

columnsIndex 或類陣列

當 data 沒有列標籤時,用於結果 DataFrame 的列標籤,預設為 RangeIndex(0, 1, 2, …, n)。如果 data 包含列標籤,則會執行列選擇。

dtypedtype,預設為 None

強制的資料型別。只允許一個 dtype。如果為 None,則推斷。如果 data 是 DataFrame,則忽略此引數。

copybool 或 None,預設為 None

從輸入中複製資料。對於 dict 資料,None 的預設行為類似於 copy=True。對於 DataFrame 或 2d ndarray 輸入,None 的預設行為類似於 copy=False。如果 data 是一個包含一個或多個 Series(可能具有不同 dtype)的字典,則 copy=False 將確保不復制這些輸入。

另請參閱

DataFrame.from_records

從元組(也包括記錄陣列)構造。

DataFrame.from_dict

從 Series、陣列或字典的字典構造。

read_csv

將逗號分隔值 (csv) 檔案讀取到 DataFrame 中。

read_table

將通用分隔檔案讀取到 DataFrame 中。

read_clipboard

將剪貼簿中的文字讀取到 DataFrame 中。

注意

請參考 使用者指南 以獲取更多資訊。

示例

從字典構造 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

從資料類構造 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

屬性

T

DataFrame 的轉置。

at

透過行/列標籤對訪問單個值。

attrs

此資料集的全域性屬性字典。

axes

返回一個表示 DataFrame 軸的列表。

columns

DataFrame 的列標籤。

資料型別

返回 DataFrame 中的資料型別。

empty

指示 Series/DataFrame 是否為空。

flags

獲取與此 pandas 物件相關的屬性。

iat

透過整數位置透過行/列對訪問單個值。

iloc

純粹基於整數位置的索引,用於按位置選擇。

index

DataFrame 的索引(行標籤)。

loc

透過標籤或布林陣列訪問一組行和列。

ndim

返回一個表示軸/陣列維數的整數。

shape

返回一個表示 DataFrame 維度的元組。

size

返回一個表示此物件中元素數量的整數。

style

返回一個 Styler 物件。

values

返回 DataFrame 的 Numpy 表示。

Methods

abs()

返回一個 Series/DataFrame,其中包含每個元素的絕對數值。

add(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素相加(二元運算子 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 的軸應用函式。

asfreq(freq[, method, how, normalize, ...])

將時間序列轉換為指定頻率。

asof(where[, subset])

返回where之前最後一個沒有 NaN 的行(或行)。

assign(**kwargs)

為 DataFrame 分配新列。

astype(dtype[, copy, errors])

將 pandas 物件強制轉換為指定的資料型別 dtype

at_time(time[, asof, axis])

選擇一天中特定時間的值(例如,上午 9:30)。

between_time(start_time, end_time[, ...])

選擇一天中特定時間段內的值(例如,上午 9:00-9:30)。

bfill(*[, axis, inplace, limit, limit_area])

使用下一個有效觀測值填充 NA/NaN 值以填補空白。

boxplot([column, by, ax, fontsize, rot, ...])

繪製 DataFrame 列的箱線圖。

clip([lower, upper, axis, inplace])

在輸入閾值處修剪值。

combine(other, func[, fill_value, overwrite])

與另一個 DataFrame 進行列組合。

combine_first(other)

other 中相同位置的值更新空值元素。

compare(other[, align_axis, keep_shape, ...])

比較另一個 DataFrame 並顯示差異。

convert_dtypes([infer_objects, ...])

將列從 numpy 資料型別轉換為支援 pd.NA 的最佳資料型別。

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, numeric_only])

沿 DataFrame 或 Series 軸返回累積最大值。

cummin([axis, skipna, numeric_only])

沿 DataFrame 或 Series 軸返回累積最小值。

cumprod([axis, skipna, numeric_only])

沿 DataFrame 或 Series 軸返回累積乘積。

cumsum([axis, skipna, numeric_only])

沿 DataFrame 或 Series 軸返回累積和。

describe([percentiles, include, exclude])

生成描述性統計資訊。

diff([periods, axis])

元素的離散差值。

div(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素浮點除法(二元運算子 truediv)。

divide(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素浮點除法(二元運算子 truediv)。

dot(other)

計算 DataFrame 和其他物件之間的矩陣乘法。

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 與其他物件逐元素等於比較(二元運算子 eq)。

equals(other)

測試兩個物件是否包含相同元素。

eval(expr, *[, inplace])

計算描述 DataFrame 列操作的字串。

ewm([com, span, halflife, alpha, ...])

提供指數加權 (EW) 計算。

expanding([min_periods, method])

提供擴充套件視窗計算。

explode(column[, ignore_index])

將列表狀元素的每個元素轉換為一行,複製索引值。

ffill(*[, axis, inplace, limit, limit_area])

透過傳播最後一個有效觀測值來填充 NA/NaN 值。

fillna(value, *[, axis, inplace, limit])

value填充 NA/NaN 值。

filter([items, like, regex, axis])

根據指定的索引標籤子集化 DataFrame 或 Series。

first_valid_index()

返回第一個非缺失值的索引,如果沒有找到值,則返回 None。

floordiv(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素整數除法(二元運算子 floordiv)。

from_arrow(data)

從表格 Arrow 物件構造 DataFrame。

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, 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])

嘗試為 object 列推斷更合適的資料型別。

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'(更多資訊請參見 Indexing)。

kurt(*[, axis, skipna, numeric_only])

返回所請求軸上的無偏峰度。

kurtosis(*[, axis, skipna, numeric_only])

返回所請求軸上的無偏峰度。

last_valid_index()

返回最後一個非缺失值的索引,如果沒有找到值,則返回 None。

le(other[, axis, level])

獲取 DataFrame 與其他物件逐元素大於等於比較(二元運算子 le)。

lt(other[, axis, level])

獲取 DataFrame 與其他物件逐元素大於比較(二元運算子 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 物件。

min(*[, axis, skipna, numeric_only])

返回所請求軸上值的最小值。

mod(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素取模(二元運算子 mod)。

mode([axis, numeric_only, dropna])

獲取所選軸上每個元素(或最常見值)。

mul(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素相乘(二元運算子 mul)。

multiply(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素相乘(二元運算子 mul)。

ne(other[, axis, level])

獲取 DataFrame 與其他物件逐元素不等於比較(二元運算子 ne)。

nlargest(n, columns[, keep])

返回按columns降序排列的前n行。

notna()

檢測存在的(非缺失)值。

notnull()

DataFrame.notnull 是 DataFrame.notna 的別名。

nsmallest(n, columns[, keep])

返回按columns升序排列的前n行。

nunique([axis, dropna])

計算指定軸上不同元素的數量。

pct_change([periods, fill_method, 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 與其他物件逐元素冪運算(二元運算子 pow)。

prod(*[, axis, skipna, numeric_only, min_count])

返回所請求軸上值的乘積。

product(*[, axis, skipna, numeric_only, ...])

返回所請求軸上值的乘積。

quantile([q, axis, numeric_only, ...])

返回所請求軸上的分位數(百分位數)值。

query(expr, *[, parser, engine, local_dict, ...])

使用布林表示式查詢 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, ...])

返回一個具有與另一個物件匹配的索引的物件。

rename([mapper, index, columns, axis, copy, ...])

重新命名列或索引標籤。

rename_axis([mapper, index, columns, axis, ...])

設定索引或列的軸名稱。

reorder_levels(order[, axis])

使用輸入order重新排列索引或列級別。

replace([to_replace, value, inplace, regex])

value替換to_replace中給定的值。

resample(rule[, closed, label, convention, ...])

對時間序列資料進行重取樣。

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])

根據列的 dtype 返回 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])

返回請求軸上的值之和。

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_hdf(path_or_buf, *, key[, mode, ...])

使用 HDFStore 將包含的資料寫入 HDF5 檔案。

to_html([buf, columns, col_space, header, ...])

將 DataFrame 渲染為 HTML 表。

to_iceberg(table_identifier[, catalog_name, ...])

將 DataFrame 寫入 Apache Iceberg 表。

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 寫入 Optimized Row Columnar (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])

將 PeriodIndex 轉換為時間戳的 DatetimeIndex,在週期的開始處。

to_xarray()

從 pandas 物件返回一個 xarray 物件。

to_xml([path_or_buffer, index, root_name, ...])

將 DataFrame 渲染為 XML 文件。

transform(func[, axis])

呼叫 func 在 self 上,生成一個與 self 具有相同軸形狀的 DataFrame。

transpose(*args[, copy])

轉置索引和列。

truediv(other[, axis, level, fill_value])

獲取 DataFrame 與其他物件逐元素浮點除法(二元運算子 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 返回橫截面。