肝了几天,十分钟入门pandas(下)

简介: 肝了几天,十分钟入门pandas(下)

简说Python,号主老表,Python终身学习者,数据分析爱好者,从18年开始分享Python知识,原创文章227篇,写过Python、SQL、Excel入门文章,也写过Web开发、数据分析文章,老表还总结整理了一份2022Python学习资料和电子书资源,关注后私信回复:2022 即可领取。

合并

Concat 连接

pandas中提供了大量的方法能够轻松对Series,DataFrame和Panel对象进行不同满足逻辑关系的合并操作

通过**concat()**来连接pandas对象

df = pd.DataFrame(np.random.randn(10,4))
df

image.png

#break it into pieces
pieces = [df[:3], df[3:7], df[7:]]
pieces

image.png

pd.concat(pieces)

image.png

Join 合并

类似于SQL中的合并(merge)

left = pd.DataFrame({'key':['foo', 'foo'], 'lval':[1,2]})
left

key lval
0 foo 1
1 foo 2
right = pd.DataFrame({'key':['foo', 'foo'], 'lval':[4,5]})
right

key lval
0 foo 4
1 foo 5
pd.merge(left, right, on='key')

key lval_x lval_y
0 foo 1 4
1 foo 1 5
2 foo 2 4
3 foo 2 5

Append 添加

将若干行添加到dataFrame后面

df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D'])
df

image.png

s = df.iloc[3]
s
A    0.163904
B    1.324567
C   -0.768324
D   -0.205520
Name: 3, dtype: float64
df.append(s, ignore_index=True)

image.png

分组

对于“group by”操作,我们通常是指以下一个或几个步骤:

  • 划分 按照某些标准将数据分为不同的组
  • 应用 对每组数据分别执行一个函数
  • 组合 将结果组合到一个数据结构
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 
                          'foo', 'bar', 'foo', 'bar'],
                   'B' : ['one', 'one', 'two', 'three', 
                          'two', 'two', 'one', 'three'],
                   'C' : np.random.randn(8),
                   'D' : np.random.randn(8)})
df

image.png

分组并对每个分组应用sum函数

df.groupby('A').sum()

C D
A

bar -0.565344 1.886637
foo 2.226542 2.122855

按多个列分组形成层级索引,然后应用函数

df.groupby(['A','B']).sum()

image.png

变形

堆叠

tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
                     'foo', 'foo', 'qux', 'qux'],
                    ['one', 'two', 'one', 'two',
                     'one', 'two', 'one', 'two']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B'])
df2 = df[:4]
df2

image.png

**stack()**方法对DataFrame的列“压缩”一个层级

stacked = df2.stack()
stacked

image.png

对于一个“堆叠过的”DataFrame或者Series(拥有MultiIndex作为索引),stack()的逆操作是unstack(),默认反堆叠到上一个层级

stacked.unstack()

image.png

stacked.unstack(1)

image.png

stacked.unstack(0)

image.png

数据透视表

df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3,
                   'B' : ['A', 'B', 'C'] * 4,
                   'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
                   'D' : np.random.randn(12),
                   'E' : np.random.randn(12)})
df

image.png

我们可以轻松地从这个数据得到透视表

pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])

image.png

时间序列

pandas在对频率转换进行重新采样时拥有着简单,强大而且高效的功能(例如把按秒采样的数据转换为按5分钟采样的数据)。这在金融领域很常见,但又不限于此。

rng = pd.date_range('1/1/2012', periods=100, freq='S')
# 看下前三条DatetimeIndex
rng[0:3]

image.png

ts = pd.Series(np.random.randint(0,500,len(rng)), index=rng)
# 看下前三条Series数据
ts[0:3]

image.png

ts.resample('5Min').sum()
2012-01-01    26203
Freq: 5T, dtype: int32

时区表示

rng = pd.date_range('3/6/2012', periods=5, freq='D')
rng
DatetimeIndex(['2012-03-06', '2012-03-07', '2012-03-08', '2012-03-09',
               '2012-03-10'],
              dtype='datetime64[ns]', freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts
2012-03-06    0.523781
2012-03-07   -0.670822
2012-03-08    0.934826
2012-03-09    0.002239
2012-03-10   -0.091952
Freq: D, dtype: float64
ts_utc = ts.tz_localize('UTC')
ts_utc
2012-03-06 00:00:00+00:00    0.523781
2012-03-07 00:00:00+00:00   -0.670822
2012-03-08 00:00:00+00:00    0.934826
2012-03-09 00:00:00+00:00    0.002239
2012-03-10 00:00:00+00:00   -0.091952
Freq: D, dtype: float64

时区转换

ts_utc.tz_convert('US/Eastern')
2012-03-05 19:00:00-05:00    0.523781
2012-03-06 19:00:00-05:00   -0.670822
2012-03-07 19:00:00-05:00    0.934826
2012-03-08 19:00:00-05:00    0.002239
2012-03-09 19:00:00-05:00   -0.091952
Freq: D, dtype: float64

时间跨度转换

rng = pd.date_range('1/1/2012', periods=5, freq='M')
rng
DatetimeIndex(['2012-01-31', '2012-02-29', '2012-03-31', '2012-04-30',
               '2012-05-31'],
              dtype='datetime64[ns]', freq='M')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts
2012-01-31    1.296132
2012-02-29    1.023936
2012-03-31   -0.249774
2012-04-30    1.007810
2012-05-31   -0.051413
Freq: M, dtype: float64
ps = ts.to_period()
ps
2012-01    1.296132
2012-02    1.023936
2012-03   -0.249774
2012-04    1.007810
2012-05   -0.051413
Freq: M, dtype: float64
ps.to_timestamp()
2012-01-01    1.296132
2012-02-01    1.023936
2012-03-01   -0.249774
2012-04-01    1.007810
2012-05-01   -0.051413
Freq: MS, dtype: float64

日期与时间戳之间的转换使得可以使用一些方便的算术函数。例如,我们把以11月为年底的季度数据转换为当前季度末月底为始的数据

prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')
prng

image.png

ts = pd.Series(np.random.randn(len(prng)), index = prng)
# 看下数据前三条
ts[0:3]

image.png

ts.index = (prng.asfreq('M', 'end') ) .asfreq('H', 'start') +9
# 看下数据前三条
ts[0:3]

image.png

分类

从版本0.15开始,pandas在DataFrame中开始包括分类数据。

df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'e', 'e']})
df

image.png

把raw_grade转换为分类类型

df["grade"] = df["raw_grade"].astype("category")
df["grade"]
0    a
1    b
2    b
3    a
4    e
5    e
Name: grade, dtype: category
Categories (3, object): [a, b, e]

重命名类别名为更有意义的名称

df["grade"].cat.categories = ["very good", "good", "very bad"]

对分类重新排序,并添加缺失的分类

df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])
df["grade"]
0    very good
1         good
2         good
3    very good
4     very bad
5     very bad
Name: grade, dtype: category
Categories (5, object): [very bad, bad, medium, good, very good]

排序是按照分类的顺序进行的,而不是字典序

df.sort_values(by="grade")

image.png

按分类分组时,也会显示空的分类

df.groupby("grade").size()
grade
very bad     2
bad          0
medium       0
good         2
very good    2
dtype: int64

绘图

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()

image.png

对于DataFrame类型,**plot()**能很方便地画出所有列及其标签

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
plt.figure(); df.plot(); plt.legend(loc='best')

image.png

获取数据的I/O

CSV

写入一个csv文件

df.to_csv('data/foo.csv')

从一个csv文件读入

df1 = pd.read_csv('data/foo.csv')
# 查看前三行数据
df1.head(3)

image.png

HDF5

HDFStores的读写

写入一个HDF5 Store

df.to_hdf('data/foo.h5', 'df')

从一个HDF5 Store读入

df1 = pd.read_hdf('data/foo.h5', 'df')
# 查看前三行数据
df1.head(3)

image.png

Excel

MS Excel的读写

写入一个Excel文件

df.to_excel('data/foo.xlsx', sheet_name='Sheet1')

从一个excel文件读入

df1 = pd.read_excel('data/foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])
# 查看前三行数据
df1.head(3)

image.png

下期见!

相关文章
|
5月前
|
数据可视化 数据挖掘 C++
一文入门数分三剑客--Numpy、Pandas、Matplotlib
一文入门数分三剑客--Numpy、Pandas、Matplotlib
|
5天前
|
索引 Python
【Pandas】- pandas入门
【Pandas】- pandas入门
|
7月前
|
索引 Python
pandas 入门
pandas 入门
90 0
pandas 入门
|
3月前
|
数据挖掘 数据处理 索引
Pandas数据处理——渐进式学习1、Pandas入门基础
Pandas数据处理——渐进式学习1、Pandas入门基础
52 0
|
7月前
|
SQL 数据挖掘 数据库
【100天精通Python】Day54:Python 数据分析_Pandas入门基础,核心数据结构Serise、DataFrame、Index对象,数据的导入操作
【100天精通Python】Day54:Python 数据分析_Pandas入门基础,核心数据结构Serise、DataFrame、Index对象,数据的导入导出操作
129 0
|
7月前
|
机器学习/深度学习 人工智能 数据挖掘
【数据分析入门】人工智能、数据分析和深度学习是什么关系?如何快速入门 Python Pandas?
【数据分析入门】人工智能、数据分析和深度学习是什么关系?如何快速入门 Python Pandas?
|
9月前
|
数据挖掘 索引 Python
使用Pandas进行数据清理的入门示例
数据清理是数据分析过程中的关键步骤,它涉及识别缺失值、重复行、异常值和不正确的数据类型。获得干净可靠的数据对于准确的分析和建模非常重要。
67 0
|
10天前
|
数据挖掘 数据处理 索引
python常用pandas函数nlargest / nsmallest及其手动实现
python常用pandas函数nlargest / nsmallest及其手动实现
25 0
|
10天前
|
Python
如何使用Python的Pandas库进行数据透视图(melt/cast)操作?
Pandas的`melt()`和`pivot()`函数用于数据透视。基本步骤:导入pandas,创建DataFrame,然后使用这两个函数变换数据。示例代码:导入pandas,定义一个包含'Name'和'Age'列的DataFrame,使用`melt()`转为长格式,再用`pivot()`恢复为宽格式。
21 1
|
11天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by='A', ascending=False)`。`rank()`函数用于计算排名,如`df['A'].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=['A', 'B'], ascending=[True, False])`和分别对'A'、'B'列排名。
24 2