一、DataFrame 本质 = 带表头 + 行号的二维表
pandas 的 DataFrame 就是一个 二维表**
它自带的所有属性,都是为了描述这个二维表的:
行、列、值、形状、类型......**
text
df.columns(列名 / 表头)
↓ ↓
'card_id' 'amount' ← 列名
┌───────┬────────┐
row 0 │ user1 │ 10 │ ← df.values[0]
row 1 │ user1 │ 20 │ ← df.values[1]
row 2 │ user2 │ 50 │ ← df.values[2]
└───────┴────────┘
↑
df.index(行索引 / 行号)
① df.index
行索引(最左边那列)
text
0
1
2
② df.columns
列名(最上面那行)
text
['card_id', 'amount']
③ df.values
纯数据(去掉行号、表头)
text
[
['user1', 10],
['user1', 20],
['user2', 50]
]
④ df.shape
几行几列
text
(3, 2) → 3行,2列
⑤ df.size
总单元格数量
text
3 × 2 = 6
⑥ df.dtypes
每一列的数据类型
text
card_id object
amount int64
DataFrame = index(行) + columns(列) + values(数据)
- 行:index
- 列:columns
- 数据:values
二、pandas 索引器
假设我们有一张表,长这样:
| 行索引(index) | card_id | amount | city |
|---|---|---|---|
| 0 | user1 | 10 | 北京 |
| 1 | user1 | 20 | 上海 |
| 2 | user2 | 50 | 广州 |
1. df['列名'] → 取列
- 对应二维表 :取出某一列/几列(竖条)
python
# 取出 amount 这一列
df['amount']
结果:
0 10
1 20
2 50
Name: amount, dtype: int64
2. df.loc['行标签'] → 按标签取行/列
python
# 1. 取行(取 index=0 那一行)
df.loc[0]
# 2. 取单元格(取第0行、city列的值)
df.loc[0, 'city']
结果:
'北京'
3. df.iloc[行号] → 按位置取行/列
python
# 1. 取行(取第0行,第1个位置的行)
df.iloc[0]
# 2. 取单元格(取第0行、第2列的值),索引列不计列数
df.iloc[0, 2]
结果:
'北京'
4. df.at['行标签', '列名'] → 快速取单个值(最快)
python
# 直接定位:行标签是0,列名是 city
df.at[0, 'city']
结果:
'北京'
"一题多解"的对比(取 user1 的第一笔金额)
| 方法 | 代码 | 结果 | 评价 |
|---|---|---|---|
| loc | df.loc[0, 'amount'] |
10 | 最推荐,可读性好 |
| iloc | df.iloc[0, 1] |
10 | 精准,知道列在第几个位置 |
| at | df.at[0, 'amount'] |
10 | 最快,只取一个值 |
三、举例
python
df.columns = cols[:1] + [co + '_hist' for co in cols[1:]]
功能:对列名重新命名
给列名批量加后缀 _hist,但第一列 card_id 保持不变!
拆解成 3 步看
① cols[:1]
保留第一列名不变
['card_id']
② cols[1:]
从第二列开始到最后的所有列
['A', 'B', 'C']
③ [co + '_hist' for co in cols[1:]]
给后面每一列都加上 _hist
['A_hist', 'B_hist', 'C_hist']
④ 拼起来
['card_id'] + ['A_hist', 'B_hist', 'C_hist']
→ ['card_id', 'A_hist', 'B_hist', 'C_hist']