DataFrame
8 methodsDataFrame 创建、索引、分组、合并与导出的核心 API。
pd.DataFrame(data)从字典、列表或二维数组创建 DataFrame。
Parameters
| Name | Type | Description |
|---|---|---|
| data | dict | list | ndarray | 输入数据 |
Returns
DataFrame — 表格数据结构
Example
pandas
import pandas as pd
df = pd.DataFrame({
"name": ["Alice", "Bob"],
"age": [30, 25],
})
print(df)pd.read_csv(filepath)读取 CSV 文件为 DataFrame。
Parameters
| Name | Type | Description |
|---|---|---|
| filepath | str | 文件路径或 URL |
Returns
DataFrame — 读取后的表格
Example
pandas
import pandas as pd
df = pd.read_csv("data.csv", encoding="utf-8")
print(df.shape)
print(df.columns)df.head(n) / df.tail(n)返回前 n 行(head)或后 n 行(tail),默认 5 行,用于快速预览。
Parameters
| Name | Type | Description |
|---|---|---|
| n | int | 返回的行数,默认 5 |
Returns
DataFrame — 前/后 n 行
Example
pandas
import pandas as pd
df = pd.read_csv("data.csv")
print(df.head(3))
print(df.tail(2))df.loc[label] / df.iloc[pos]loc 按标签索引,iloc 按整数位置索引行/列。
Parameters
| Name | Type | Description |
|---|---|---|
| label | str | list | 行/列标签 |
| position | int | list | 整数位置 |
Returns
Series | DataFrame — 索引结果
Example
pandas
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]}, index=["x", "y", "z"])
print(df.loc["y"])
print(df.iloc[0])df.groupby(by)按指定列分组,常与聚合函数链式使用。
Parameters
| Name | Type | Description |
|---|---|---|
| by | str | list | 分组依据的列名 |
Returns
DataFrameGroupBy — 分组对象
Example
pandas
import pandas as pd
df = pd.DataFrame({
"dept": ["A", "A", "B", "B"],
"salary": [100, 200, 150, 250],
})
print(df.groupby("dept")["salary"].mean())df.merge(other, on)按指定列与另一个 DataFrame 合并,类似 SQL JOIN。
Parameters
| Name | Type | Description |
|---|---|---|
| other | DataFrame | 右侧待合并的表 |
| on | str | list | 连接键列名 |
Returns
DataFrame — 合并后的表
Example
pandas
import pandas as pd
left = pd.DataFrame({"id": [1, 2], "name": ["A", "B"]})
right = pd.DataFrame({"id": [1, 2], "age": [20, 30]})
merged = left.merge(right, on="id")
print(merged)df.apply(func)对行或列应用函数,返回变换后的结果。
Parameters
| Name | Type | Description |
|---|---|---|
| func | Callable | 应用于每行/列的函数 |
Returns
Series | DataFrame — 函数应用结果
Example
pandas
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(lambda col: col.max() - col.min()))
print(df.apply(lambda row: row["a"] + row["b"], axis=1))df.to_csv(filepath)将 DataFrame 写入 CSV 文件。
Parameters
| Name | Type | Description |
|---|---|---|
| filepath | str | 输出文件路径 |
Returns
None — 写入文件(返回写入行数或 None)
Example
pandas
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
df.to_csv("out.csv", index=False)
print("done")