pandas利用pd.Index和df.reindex函数提取相应列

该博客内容涉及数据集的处理,使用pandas库中的Index函数提取特定列,包括实际GDP(realgdp)、通货膨胀率(infl)和失业率(unemp)。通过重新索引列,生成了一个新的DataFrame,专注于经济指标的变化和分析。
摘要由CSDN通过智能技术生成

假设存在以下数据集

   realgdp 	realcons 	realinv 	realgovt 	realdpi 	cpi 	m1 	tbilrate 	unemp 	pop 	infl 	realint
0 	2710.349 	1707.4 	286.898 	470.045 	1886.9 	28.98 	139.7 	2.82 	5.8 	177.146 	0.00 	0.00
1 	2778.801 	1733.7 	310.859 	481.301 	1919.7 	29.15 	141.7 	3.08 	5.1 	177.830 	2.34 	0.74
2 	2775.488 	1751.8 	289.226 	491.260 	1916.4 	29.35 	140.5 	3.82 	5.3 	178.657 	2.74 	1.09
3 	2785.204 	1753.7 	299.356 	484.052 	1931.3 	29.37 	140.0 	4.33 	5.6 	179.386 	0.27 	4.06
4 	2847.699 	1770.5 	331.722 	462.199 	1955.5 	29.54 	139.6 	3.50 	5.2 	180.007 	2.31 	1.19

要提取以下列,使用Index函数

columns = pd.Index(['realgdp', 'infl', 'unemp'], name='item')

重新对列索引

data = df.reindex(columns=columns)

生成新Dataframe

item realgdp 	infl 	unemp
0 	2710.349 	0.00 	5.8
1 	2778.801 	2.34 	5.1
2 	2775.488 	2.74 	5.3
3 	2785.204 	0.27 	5.6
4 	2847.699 	2.31 	5.2
`df.pivot`、`df.reindex` 和 `df.align` 的区别如下: 1. `df.pivot` 用于根据给定的索引/值对重新构造DataFrame,返回一个新的DataFrame对象。而 `df.reindex` 用于对行或进行重新标记,并返回具有新索引的DataFrame对象。 2. `df.pivot` 可以使用聚合函数来汇总重复索引/值的数据,而 `df.reindex` 不会进行这样的操作。 3. `df.align` 用于沿着指定的轴对齐两个对象,并返回一个元组,包含两个对象的重新索引版本。 下面是 `df.pivot` 和 `df.reindex` 的使用示例: 引用:df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E']) [^1] ```python import pandas as pd import numpy as np # 创建一个 DataFrame df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C': np.random.randn(8), 'D': np.random.randn(8)}) # 对 DataFrame 进行重新索引 df1 = df.reindex(index=range(4), columns=list(df.columns) + ['E']) print(df1) ``` 输出结果: ``` A B C D E 0 foo one 0.884294 0.848049 NaN 1 bar one -0.252554 0.760753 NaN 2 foo two 0.062926 -0.225259 NaN 3 bar three 0.055329 0.785876 NaN ``` 引用:pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C']) [^1] ```python import pandas as pd import numpy as np # 创建一个 DataFrame df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C': np.random.randn(8), 'D': np.random.randn(8)}) # 使用 pivot_table() 聚合数据 pv = pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C']) print(pv) ``` 输出结果: ``` C -0.902191 0.101844 0.228387 ... 1.300993 1.588940 1.756183 A B ... bar one NaN NaN 0.011764 ... NaN NaN NaN three NaN NaN NaN ... NaN NaN NaN two 1.208722 NaN NaN ... NaN NaN NaN foo one -1.459425 NaN NaN ... NaN NaN NaN three NaN NaN NaN ... NaN NaN -0.335457 two NaN -0.877678 NaN ... 1.057251 0.183236 NaN [6 rows x 8 columns] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值