Pandas教程(pandas用法)

pandas用法-全网最详细教程 如果传入的是字典,则按排序后的键连接,除非传入了 keys 参数,这种情况下会选择字典中的值。任何没有反对的对象会被忽略,除非它们都是 None,这种情况下会引发 ValueError。如果为 True,则不使用连接轴上的索引值。如果连接的对象在连接轴上没有有意义的索引信息,这个参数非常有用。join: 字符串,'inner' 或 'outer',默认值为 'outer'。levels: 序列的列表,默认值为 None。用于指定其他轴上的具体索引,而不是执行内部/外部连接逻辑。生成的分层索引中的级别名称。 阅读详情
AI摘要

本文全面介绍了Pandas库的基本概念,包括Series和DataFrame的使用,数据筛选、设置和处理丢失数据的方法,以及数据导入导出、合并和绘图等功能,是Python数据分析入门的必备指南。

Pandas 基本介绍

Numpy 和 Pandas 有什么不同
如果用 python 的列表和字典来作比较, 那么可以说 Numpy 是列表形式的,没有数值标签,而 Pandas 就是字典形式。Pandas是基于Numpy构建的,让Numpy为中心的应用变得更加简单。
要使用pandas,首先需要了解他主要两个数据结构:Series和DataFrame。
Series

import pandas as pd
import numpy as np
s = pd.Series([1,3,6,np.nan,44,1])

print(s)
"""
0     1.0
1     3.0
2     6.0
3     NaN
4    44.0
5     1.0
dtype: float64
"""

Series的字符串表现形式为:索引在左边,值在右边。由于我们没有为数据指定索引。于是会自动创建一个0到N-1(N为长度)的整数型索引。

DataFrame 
dates = pd.date_range('20160101',periods=6)
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d'])

print(df)
"""
                   a         b         c         d
2016-01-01 -0.253065 -2.071051 -0.640515  0.613663
2016-01-02 -1.147178  1.532470  0.989255 -0.499761
2016-01-03  1.221656 -2.390171  1.862914  0.778070
2016-01-04  1.473877 -0.046419  0.610046  0.204672
2016-01-05 -1.584752 -0.700592  1.487264 -1.778293
2016-01-06  0.633675 -1.414157 -0.277066 -0.442545
"""

DataFrame是一个表格型的数据结构,它包含有一组有序的列,每列可以是不同的值类型(数值,字符串,布尔值等)。DataFrame既有行索引也有列索引, 它可以被看做由Series组成的大字典。
我们可以根据每一个不同的索引来挑选数据, 比如挑选 b 的元素:
DataFrame 的一些简单运用

print(df['b'])

"""
2016-01-01   -2.071051
2016-01-02    1.532470
2016-01-03   -2.390171
2016-01-04   -0.046419
2016-01-05   -0.700592
2016-01-06   -1.414157
Freq: D, Name: b, dtype: float64
"""

我们在创建一组没有给定行标签和列标签的数据 df1:

df1 = pd.DataFrame(np.arange(12).reshape((3,4)))
print(df1)

"""
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
"""

这样,他就会采取默认的从0开始 index. 还有一种生成 df 的方法, 如下 df2:

df2 = pd.DataFrame({'A': 1.,
                    'B': pd.Timestamp('20200102'),
                    'C': pd.Series(1, index=list(range(4)), dtype='float32'),
                    'D': np.array([3] * 4, dtype='int32'),
                    'E': pd.Categorical(["test", "train", "test", "train"]),
                    'F': 'foo'})

print(df2)

"""
     A          B    C  D      E    F
0  1.0 2020-01-02  1.0  3   test  foo
1  1.0 2020-01-02  1.0  3  train  foo
2  1.0 2020-01-02  1.0  3   test  foo
3  1.0 2020-01-02  1.0  3  train  foo
"""

这种方法能对每一列的数据进行特殊对待. 如果想要查看数据中的类型, 我们可以用 dtype这个属性:

print(df2.dtypes)

"""
df2.dtypes
A           float64
B    datetime64[ns]
C           float32
D             int32
E          category
F            object
dtype: object
"""

如果想看对列的序号:

print(df2.index)

 Int64Index([0, 1, 2, 3], dtype='int64')

同样, 每种数据的名称也能看到:

print(df2.columns)

 Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')
如果只想看所有df2的值:
print(df2.values)

"""
array([[1.0, Timestamp('2020-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2020-01-02 00:00:00'), 1.0, 3, 'train', 'foo'],
       [1.0, Timestamp('2020-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2020-01-02 00:00:00'), 1.0, 3, 'train', 'foo']], dtype=object)
"""

想知道数据的总结, 可以用 describe():

df2.describe()

"""
         A    C    D
count  4.0  4.0  4.0
mean   1.0  1.0  3.0
std    0.0  0.0  0.0
min    1.0  1.0  3.0
25%    1.0  1.0  3.0
50%    1.0  1.0  3.0
75%    1.0  1.0  3.0
max    1.0  1.0  3.0
"""

如果想翻转数据, transpose:

print(df2.T)

"""                   
0                    1                    2  \
A                    1                    1                    1   
B  2020-01-02 00:00:00  2020-01-02 00:00:00  2020-01-02 00:00:00   
C                    1                    1                    1   
D                    3                    3                    3   
E                 test                train                 test   
F                  foo                  foo                  foo   

                     3  
A                    1  
B  2020-01-02 00:00:00  
C                    1  
D                    3  
E                train  
F                  foo  

"""

如果想对数据的 index 进行排序并输出:

print(df2.sort_index(axis=1, ascending=False))

"""
     F      E  D    C          B    A
0  foo   test  3  1.0 2020-01-02  1.0
1  foo  train  3  1.0 2020-01-02  1.0
2  foo   test  3  1.0 2020-01-02  1.0
3  foo  train  3  1.0 2020-01-02  1.0
"""

如果是对数据 值 排序输出:

print(df2.sort_values(by='B'))

"""
     A          B    C  D      E    F
0  1.0 2020-01-02  1.0  3   test  foo
1  1.0 2020-01-02  1.0  3  train  foo
2  1.0 2020-01-02  1.0  3   test  foo
3  1.0 2020-01-02  1.0  3  train  foo
"""

Pandas 选择数据

我们建立了一个 6X4 的矩阵数据。

dates = pd.date_range('20200101', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6,4)),index=dates, columns=['A','B','C','D'])

"""
             A   B   C   D
2020-01-01   0   1   2   3
2020-01-02   4   5   6   7
2020-01-03   8   9  10  11
2020-01-04  12  13  14  15
2020-01-05  16  17  18  19
2020-01-06  20  21  22  23
"""

简单的筛选
如果我们想选取DataFrame中的数据,下面描述了两种途径, 他们都能达到同一个目的:

print(df['A'])
print(df.A)

"""
2020-01-01     0
2020-01-02     4
2020-01-03     8
2020-01-04    12
2020-01-05    16
2020-01-06    20
Freq: D, Name: A, dtype: int64
"""

让选择跨越多行或多列:

print(df[0:3])

"""
            A  B   C   D
2020-01-01  0  1   2   3
2020-01-02  4  5   6   7
2020-01-03  8  9  10  11
"""

print(df['20200102':'20200104'])

"""
A   B   C   D
2020-01-02   4   5   6   7
2020-01-03   8   9  10  11
2020-01-04  12  13  14  15
"""

如果df[3:3]将会是一个空对象。后者选择20200102到20200104标签之间的数据,并且包括这两个标签。
根据标签 loc
同样我们可以使用标签来选择数据 loc, 本例子主要通过标签名字选择某一行数据, 或者通过选择某行或者所有行(:代表所有行)然后选其中某一列或几列数据。:

print(df.loc['20200102'])
"""
A    4
B    5
C    6
D    7
Name: 2020-01-02 00:00:00, dtype: int64
"""

print(df.loc[:,['A','B']]) 
"""
             A   B
2020-01-01   0   1
2020-01-02   4   5
2020-01-03   8   9
2020-01-04  12  13
2020-01-05  16  17
2020-01-06  20  21
"""

print(df.loc['20200102',['A','B']])
"""
A    4
B    5
Name: 2020-01-02 00:00:00, dtype: int64
"""

根据序列 iloc
另外我们可以采用位置进行选择 iloc, 在这里我们可以通过位置选择在不同情况下所需要的数据例如选某一个,连续选或者跨行选等操作。

print(df.iloc[3,1])
 13

print(df.iloc[3:5,1:3])
"""
             B   C
2020-01-04  13  14
2020-01-05  17  18
"""

print(df.iloc[[1,3,5],1:3])
"""
             B   C
2020-01-02   5   6
2020-01-04  13  14
2020-01-06  21  22

"""

在这里我们可以通过位置选择在不同情况下所需要的数据, 例如选某一个,连续选或者跨行选等操作。
根据混合的这两种 ix
当然我们可以采用混合选择 ix, 其中选择’A’和’C’的两列,并选择前三行的数据。

print(df.ix[:3,['A','C']])
"""
            A   C
2020-01-01  0   2
2020-01-02  4   6
2020-01-03  8  10
"""

通过判断的筛选
最后我们可以采用判断指令 (Boolean indexing) 进行选择. 我们可以约束某项条件然后选择出当前所有数据.

print(df[df.A>8])
"""
             A   B   C   D
2020-01-04  12  13  14  15
2020-01-05  16  17  18  19
2020-01-06  20  21  22  23
"""

Pandas 设置值

创建数据
我们可以根据自己的需求, 用 pandas 进行更改数据里面的值, 或者加上一些空的,或者有数值的列.
首先建立了一个 6X4 的矩阵数据。

dates = pd.date_range('20200101', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6,4)),index=dates, columns=['A','B','C','D'])

"""
             A   B   C   D
2020-01-01   0   1   2   3
2020-01-02   4   5   6   7
2020-01-03   8   9  10  11
2020-01-04  12  13  14  15
2020-01-05  16  17  18  19
2020-01-06  20  21  22  23
"""

根据位置设置 loc 和 iloc
我们可以利用索引或者标签确定需要修改值的位置。

df.iloc[2,2] = 1111
df.loc['20200101','B'] = 2222

"""
             A     B     C   D
2020-01-01   0  2222     2   3
2020-01-02   4     5     6   7
2020-01-03   8     9  1111  11
2020-01-04  12    13    14  15
2020-01-05  16    17    18  19
2020-01-06  20    21    22  23
"""

根据条件设置
如果现在的判断条件是这样, 我们想要更改B中的数, 而更改的位置是取决于 A 的. 对于A大于4的位置. 更改B在相应位置上的数为0.

df.B[df.A>4] = 0
"""
                A     B     C   D
2020-01-01   0  2222     2   3
2020-01-02   4     5     6   7
2020-01-03   8     0  1111  11
2020-01-04  12     0    14  15
2020-01-05  16     0    18  19
2020-01-06  20     0    22  23 
"""
按行或列设置 
如果对整列做批处理, 加上一列 'F', 并将 F 列全改为 NaN, 如下:
df['F'] = np.nan
"""
             A     B     C   D   F
2020-01-01   0  2222     2   3 NaN
2020-01-02   4     5     6   7 NaN
2020-01-03   8     0  1111  11 NaN
2020-01-04  12     0    14  15 NaN
2020-01-05  16     0    18  19 NaN
2020-01-06  20     0    22  23 NaN
"""
添加数据 
用上面的方法也可以加上 Series 序列(但是长度必须对齐)。
df['E'] = pd.Series([1,2,3,4,5,6], index=pd.date_range('20200101',periods=6)) 
"""
             A     B     C   D   F  E
2020-01-01   0  2222     2   3 NaN  1
2020-01-02   4     5     6   7 NaN  2
2020-01-03   8     0  1111  11 NaN  3
2020-01-04  12     0    14  15 NaN  4
2020-01-05  16     0    18  19 NaN  5
2020-01-06  20     0    22  23 NaN  6
"""

这样我们大概学会了如何对DataFrame中在自己想要的地方赋值或者增加数据。

Pandas 处理丢失数据

创建含 NaN 的矩阵
有时候我们导入或处理数据, 会产生一些空的或者是 NaN 数据,如何删除或者是填补这些 NaN 数据就是我们今天所要提到的内容.
建立了一个6X4的矩阵数据并且把两个位置置为空.

dates = pd.date_range('20200101', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6,4)),index=dates, columns=['A','B','C','D'])
df.iloc[0,1] = np.nan
df.iloc[1,2] = np.nan
"""
             A     B     C   D
2020-01-01   0   NaN   2.0   3
2020-01-02   4   5.0   NaN   7
2020-01-03   8   9.0  10.0  11
2020-01-04  12  13.0  14.0  15
2020-01-05  16  17.0  18.0  19
2020-01-06  20  21.0  22.0  23
"""
pd.dropna() 

如果想直接去掉有 NaN 的行或列, 可以使用 dropna

df.dropna(
    axis=0,     # 0: 对行进行操作; 1: 对列进行操作
    how='any'   # 'any': 只要存在 NaN 就 drop 掉; 'all': 必须全部是 NaN 才 drop 
    ) 
"""
             A     B     C   D
2020-01-03   8   9.0  10.0  11
2020-01-04  12  13.0  14.0  15
2020-01-05  16  17.0  18.0  19
2020-01-06  20  21.0  22.0  23
"""
pd.fillna() 

如果是将 NaN 的值用其他值代替, 比如代替成 0:

df.fillna(value=0)
"""
             A     B     C   D
2020-01-01   0   0.0   2.0   3
2020-01-02   4   5.0   0.0   7
2020-01-03   8   9.0  10.0  11
2020-01-04  12  13.0  14.0  15
2020-01-05  16  17.0  18.0  19
2020-01-06  20  21.0  22.0  23
"""
pd.isnull() 

判断是否有缺失数据 NaN, 为 True 表示缺失数据:

df.isnull() 
"""
                A      B      C      D
2020-01-01  False   True  False  False
2020-01-02  False  False   True  False
2020-01-03  False  False  False  False
2020-01-04  False  False  False  False
2020-01-05  False  False  False  False
2020-01-06  False  False  False  False
"""

检测在数据中是否存在 NaN, 如果存在就返回 True:

np.any(df.isnull()) == True  
 True

Pandas 导入导出

要点
pandas可以读取与存取的资料格式有很多种,像csv、excel、json、html与pickle等…, 详细请看官方说明文件
在这里插入图片描述

读取csv

import pandas as pd #加载模块

#读取csv
data = pd.read_csv('student.csv')

#打印出data
print(data)

将资料存取成pickle

data.to_pickle('student.pickle')

Pandas 合并 concat

pandas处理多组数据的时候往往会要用到数据的合并处理,使用 concat是一种基本的合并方式.而且concat中有很多参数可以调整,合并成你想要的数据形式.
axis (合并方向)
axis=0是预设值,因此未设定任何参数时,函数默认axis=0。

import pandas as pd
import numpy as np

#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*2, columns=['a','b','c','d'])

#concat纵向合并
res = pd.concat([df1, df2, df3], axis=0)

#打印结果
print(res)
    a    b    c    d
 0  0.0  0.0  0.0  0.0
 1  0.0  0.0  0.0  0.0
 2  0.0  0.0  0.0  0.0
 0  1.0  1.0  1.0  1.0
 1  1.0  1.0  1.0  1.0
 2  1.0  1.0  1.0  1.0
 0  2.0  2.0  2.0  2.0
 1  2.0  2.0  2.0  2.0
 2  2.0  2.0  2.0  2.0

仔细观察会发现结果的index是0, 1, 2, 0, 1, 2, 0, 1, 2,若要将index重置,请看例子二。
ignore_index (重置 index)

#承上一个例子,并将index_ignore设定为True
res = pd.concat([df1, df2, df3], axis=0, ignore_index=True)

#打印结果
print(res)
    a    b    c    d
 0  0.0  0.0  0.0  0.0
 1  0.0  0.0  0.0  0.0
 2  0.0  0.0  0.0  0.0
 3  1.0  1.0  1.0  1.0
 4  1.0  1.0  1.0  1.0
 5  1.0  1.0  1.0  1.0
 6  2.0  2.0  2.0  2.0
 7  2.0  2.0  2.0  2.0
 8  2.0  2.0  2.0  2.0

结果的index变0, 1, 2, 3, 4, 5, 6, 7, 8。
join (合并方式)
join='outer’为预设值,因此未设定任何参数时,函数默认join=‘outer’。此方式是依照column来做纵向合并,有相同的column上下合并在一起,其他独自的column个自成列,原本没有值的位置皆以NaN填充。

import pandas as pd
import numpy as np

#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d','e'], index=[2,3,4])

#纵向"外"合并df1与df2
res = pd.concat([df1, df2], axis=0, join='outer')

print(res)
     a    b    c    d    e
 1  0.0  0.0  0.0  0.0  NaN
 2  0.0  0.0  0.0  0.0  NaN
 3  0.0  0.0  0.0  0.0  NaN
 2  NaN  1.0  1.0  1.0  1.0
 3  NaN  1.0  1.0  1.0  1.0
 4  NaN  1.0  1.0  1.0  1.0

原理同上个例子的说明,但只有相同的column合并在一起,其他的会被抛弃。

#承上一个例子

#纵向"内"合并df1与df2
res = pd.concat([df1, df2], axis=0, join='inner')

#打印结果
print(res)
     b    c    d
1  0.0  0.0  0.0
 2  0.0  0.0  0.0
 3  0.0  0.0  0.0
 2  1.0  1.0  1.0
 3  1.0  1.0  1.0
 4  1.0  1.0  1.0

#重置index并打印结果
res = pd.concat([df1, df2], axis=0, join='inner', ignore_index=True)
print(res)
     b    c    d
 0  0.0  0.0  0.0
 1  0.0  0.0  0.0
 2  0.0  0.0  0.0
 3  1.0  1.0  1.0
 4  1.0  1.0  1.0
 5  1.0  1.0  1.0

join_axes (依照 axes 合并)

import pandas as pd
import numpy as np

#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d','e'], index=[2,3,4])

#依照`df1.index`进行横向合并
res = pd.concat([df1, df2], axis=1, join_axes=[df1.index])

#打印结果
print(res)
     a    b    c    d    b    c    d    e
 1  0.0  0.0  0.0  0.0  NaN  NaN  NaN  NaN
 2  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
 3  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0

#移除join_axes,并打印结果
res = pd.concat([df1, df2], axis=1)
print(res)
     a    b    c    d    b    c    d    e
#1  0.0  0.0  0.0  0.0  NaN  NaN  NaN  NaN
 2  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
 3  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
 4  NaN  NaN  NaN  NaN  1.0  1.0  1.0  1.0
append (添加数据) 
append只有纵向合并,没有横向合并。
import pandas as pd
import numpy as np

#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
s1 = pd.Series([1,2,3,4], index=['a','b','c','d'])

#将df2合并到df1的下面,以及重置index,并打印出结果
res = df1.append(df2, ignore_index=True)
print(res)
    a    b    c    d
 0  0.0  0.0  0.0  0.0
 1  0.0  0.0  0.0  0.0
 2  0.0  0.0  0.0  0.0
 3  1.0  1.0  1.0  1.0
 4  1.0  1.0  1.0  1.0
 5  1.0  1.0  1.0  1.0

#合并多个df,将df2与df3合并至df1的下面,以及重置index,并打印出结果
res = df1.append([df2, df3], ignore_index=True)
print(res)
     a    b    c    d
 0  0.0  0.0  0.0  0.0
 1  0.0  0.0  0.0  0.0
 2  0.0  0.0  0.0  0.0
 3  1.0  1.0  1.0  1.0
4  1.0  1.0  1.0  1.0
 5  1.0  1.0  1.0  1.0
 6  1.0  1.0  1.0  1.0
 7  1.0  1.0  1.0  1.0
 8  1.0  1.0  1.0  1.0

合并series,将s1合并至df1,以及重置index,并打印出结果
r

es = df1.append(s1, ignore_index=True)
print(res)
     a    b    c    d
 0  0.0  0.0  0.0  0.0
 1  0.0  0.0  0.0  0.0
 2  0.0  0.0  0.0  0.0
#3  1.0  2.0  3.0  4.0

Pandas 合并 merge

要点
pandas中的merge和concat类似,但主要是用于两组有key column的数据,统一索引的数据. 通常也被用在Database的处理当中.
依据一组key合并

import pandas as pd

#定义资料集并打印出
left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
                             'A': ['A0', 'A1', 'A2', 'A3'],
                             'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
                              'C': ['C0', 'C1', 'C2', 'C3'],
                              'D': ['D0', 'D1', 'D2', 'D3']})

print(left)
    A   B key
 0  A0  B0  K0
 1  A1  B1  K1
 2  A2  B2  K2
 3  A3  B3  K3

print(right)
    C   D key
 0  C0  D0  K0
 1  C1  D1  K1
 2  C2  D2  K2
 3  C3  D3  K3

#依据key column合并,并打印出
res = pd.merge(left, right, on='key')

print(res)
     A   B key   C   D
 0  A0  B0  K0  C0  D0
 1  A1  B1  K1  C1  D1
 2  A2  B2  K2  C2  D2
 3  A3  B3  K3  C3  D3

依据两组key合并
合并时有4种方法how = [‘left’, ‘right’, ‘outer’, ‘inner’],预设值how=‘inner’。

import pandas as pd

#定义资料集并打印出
left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
                      'key2': ['K0', 'K1', 'K0', 'K1'],
                      'A': ['A0', 'A1', 'A2', 'A3'],
                      'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
                       'key2': ['K0', 'K0', 'K0', 'K0'],
                       'C': ['C0', 'C1', 'C2', 'C3'],
                       'D': ['D0', 'D1', 'D2', 'D3']})

print(left)
    A   B key1 key2
 0  A0  B0   K0   K0
1  A1  B1   K0   K1
 2  A2  B2   K1   K0
 3  A3  B3   K2   K1

print(right)
    C   D key1 key2
 0  C0  D0   K0   K0
 1  C1  D1   K1   K0
 2  C2  D2   K1   K0
 3  C3  D3   K2   K0

#依据key1与key2 columns进行合并,并打印出四种结果['left', 'right', 'outer', 'inner']
res = pd.merge(left, right, on=['key1', 'key2'], how='inner')
print(res)
   A   B key1 key2   C   D
 0  A0  B0   K0   K0  C0  D0
 1  A2  B2   K1   K0  C1  D1
 2  A2  B2   K1   K0  C2  D2

res = pd.merge(left, right, on=['key1', 'key2'], how='outer')
print(res)
     A    B key1 key2    C    D
 0   A0   B0   K0   K0   C0   D0
 1   A1   B1   K0   K1  NaN  NaN
 2   A2   B2   K1   K0   C1   D1
 3   A2   B2   K1   K0   C2   D2
 4   A3   B3   K2   K1  NaN  NaN
 5  NaN  NaN   K2   K0   C3   D3

res = pd.merge(left, right, on=['key1', 'key2'], how='left')
print(res)
    A   B key1 key2    C    D
 0  A0  B0   K0   K0   C0   D0
 1  A1  B1   K0   K1  NaN  NaN
 2  A2  B2   K1   K0   C1   D1# 3  A2  B2   K1   K0   C2   D2
 4  A3  B3   K2   K1  NaN  NaN

res = pd.merge(left, right, on=['key1', 'key2'], how='right')
print(res)
     A    B key1 key2   C   D
 0   A0   B0   K0   K0  C0  D0
 1   A2   B2   K1   K0  C1  D1
 2   A2   B2   K1   K0  C2  D2
 3  NaN  NaN   K2   K0  C3  D3
Indicator 
indicator=True会将合并的记录放在新的一列。
import pandas as pd

#定义资料集并打印出
df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b']})
df2 = pd.DataFrame({'col1':[1,2,2],'col_right':[2,2,2]})

print(df1)
   col1 col_left
 0     0        a
 1     1        b

print(df2)
  col1  col_right
 0     1          2
 1     2          2
2     2          2

依据col1进行合并,并启用indicator=True,最后打印出

res = pd.merge(df1, df2, on='col1', how='outer', indicator=True)
print(res)
   col1 col_left  col_right      _merge
 0   0.0        a        NaN   left_only
 1   1.0        b        2.0        both
 2   2.0      NaN        2.0  right_only
 3   2.0      NaN        2.0  right_only

 自定indicator column的名称,并打印出
res = pd.merge(df1, df2, on='col1', how='outer', indicator='indicator_column')
print(res)
   col1 col_left  col_right indicator_column
 0   0.0        a        NaN        left_only
 1   1.0        b        2.0             both
 2   2.0      NaN        2.0       right_only
 3   2.0      NaN        2.0       right_only
依据index合并 
import pandas as pd

#定义资料集并打印出
left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
                     'B': ['B0', 'B1', 'B2']},
                     index=['K0', 'K1', 'K2'])
right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
                      'D': ['D0', 'D2', 'D3']},
                     index=['K0', 'K2', 'K3'])

print(left)
     A   B
 K0  A0  B0
 K1  A1  B1
 K2  A2  B2

print(right)
     C   D
 K0  C0  D0
 K2  C2  D2
 K3  C3  D3

#依据左右资料集的index进行合并,how='outer',并打印出
res = pd.merge(left, right, left_index=True, right_index=True, how='outer')
print(res)
      A    B    C    D
 K0   A0   B0   C0   D0
 K1   A1   B1  NaN  NaN
 K2   A2   B2   C2   D2
 K3  NaN  NaN   C3   D3

#依据左右资料集的index进行合并,how='inner',并打印出
res = pd.merge(left, right, left_index=True, right_index=True, how='inner')
print(res)
     A   B   C   D
 K0  A0  B0  C0  D0
 K2  A2  B2  C2  D2

解决overlapping的问题

import pandas as pd

#定义资料集
boys = pd.DataFrame({'k': ['K0', 'K1', 'K2'], 'age': [1, 2, 3]})
girls = pd.DataFrame({'k': ['K0', 'K0', 'K3'], 'age': [4, 5, 6]})

#使用suffixes解决overlapping的问题
res = pd.merge(boys, girls, on='k', suffixes=['_boy', '_girl'], how='inner')
print(res)
  age_boy   k  age_girl
 0        1  K0         4
 1        1  K0         5

Pandas plot 出图

这次我们讲如何将数据可视化. 首先import我们需要用到的模块,除了 pandas,我们也需要使用 numpy 生成一些数据,这节里使用的 matplotlib 仅仅是用来 show 图片的, 即

plt.show()。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

今天我们主要是学习如何 plot data
创建一个Series
这是一个线性的数据,我们随机生成1000个数据,Series 默认的 index 就是从0开始的整数,但是这里我显式赋值以便让大家看的更清楚
随机生成1000个数据

data = pd.Series(np.random.randn(1000), index=np.arange(1000))

为了方便观看效果, 我们累加这个数据

data.cumsum()

#pandas 数据可以直接观看其可视化形式


data.plot()

plt.show()

就这么简单,熟悉 matplotlib 的朋友知道如果需要plot一个数据,我们可以使用 plt.plot(x=, y=),把x,y的数据作为参数存进去,但是data本来就是一个数据,所以我们可以直接plot。 生成的结果就是下图:
在这里插入图片描述

Dataframe 可视化
我们生成一个1000*4 的DataFrame,并对他们累加

data = pd.DataFrame(
    np.random.randn(1000,4),
    index=np.arange(1000),
    columns=list("ABCD")
    )
data.cumsum()
data.plot()
plt.show()

在这里插入图片描述

这个就是我们刚刚生成的4个column的数据,因为有4组数据,所以4组数据会分别plot出来。plot 可以指定很多参数,具体的用法大家可以自己查一下这里
除了plot,我经常会用到还有scatter,这个会显示散点图,首先给大家说一下在 pandas 中有多少种方法
• bar
• hist
• box
• kde
• area
• scatter
• hexbin
但是我们今天不会一一介绍,主要说一下 plot 和 scatter. 因为scatter只有x,y两个属性,我们我们就可以分别给x, y指定数据
ax = data.plot.scatter(x=‘A’,y=‘B’,color=‘DarkBlue’,label=‘Class1’)
然后我们在可以再画一个在同一个ax上面,选择不一样的数据列,不同的 color 和 label
#将之下这个 data 画在上一个 ax 上面

data.plot.scatter(x='A',y='C',color='LightGreen',label='Class2',ax=ax)
plt.show()

下面就是我plot出来的图片
在这里插入图片描述

这就是两种呈现方式,一种是线性的方式,一种是散点图。

【pandas教程】pandas的类SQL用法 pandas类SQL用法总结 阅读详情

相关推荐

sdio wifi 移植

介绍 简单来说,sdio起源自sd标准,顾名思义就是sd的IO接口(interface)的意思,更具体的说明,sd本来是记忆卡的标准,但是现在也可以把SD卡拿来插上一些外围设备接口使用,这个就是就叫做sdio。 而且sdio本身是一种相当单纯的技术,通过sd的IO引脚来连接外部外围,并且通过sd的IO数据接位与外围传输数据,而且sd协会也推出很完整的sdio stack 驱动程序,使得sdio外围得开发与应用变得非常热门 这里我们要移植的是RTL8822cs的sdio WiFi 模块,将其移植到rk3

Enosji的博客 9612

Pandas之:Pandas简洁教程

Pandas之:Pandas简洁教程 目录简介对象创建查看数据选择数据loc和iloc布尔索引处理缺失数据合并分组 简介优惠券免费领取 www.fenfaw.cn pandas是建立在Python编程语言之上的一种快速,强大,灵活且易于使用的开源数据分析和处理工具,它含有使数据清洗和分析⼯ 作变得更快更简单的数据结构和操作⼯具。pandas经常和其它⼯具⼀同使⽤,如数值计算⼯具NumPy和SciPy,分析库statsmodels和scikit-learn,和数据可视化库matplotlib等。 panda.

nidongla的博客 1089

嵌入式SD/TF卡通用协议-SDIO协议

为了驱动SD卡,首先的第一步就是观察SD卡引脚接线情况,通常我们在画原理图时,都是使用的SD卡卡槽与MCU进行接线。SD卡可以使用SDIO协议和SPI协议进行通信,这里我们主要介绍SDIO协议。下图中的TF卡只是容量小一点的SD卡。以F1C100S为例,接线图如下所示:我们发现上图中的TF卡使用的协议为SDIO协议,主要有4根数据线,1根命令线,1根时钟线组合而成。为了驱动这个SD/TF卡我们就需要去了解SDIO协议的时序。

qq_1033275663的博客 3052

翻译:Panda3D Manual/V. Programming with Panda/A. The Scene Graph

场景组织Scene Graph节点树很多简单3维引擎都使用一个模型列表(list)来组织场景,渲染时首先分配(或从磁盘载入)一个3维模型然后插入模型列表。在没有插入列表之前,模型对渲染器(render)来说是“不可见”的。Panda3D的场景组织要复杂一些,它使用树结构而不是列表。同理,插入到树里之前,物体对渲染器不可见。这棵树由PandaNode类的对象构成,该类作为ModelN

python二级题库 3114

ROS环境下UR机械臂与Realsense相机手眼标定实战指南

本文提供了在ROS环境下,对UR机械臂与Realsense相机进行手眼标定的完整实战指南。详细介绍了从环境搭建、软件包安装、硬件配置到分步数据采集与计算的完整流程,并分享了常见的避坑技巧与精度优化方法,旨在帮助开发者高效、准确地完成标定,为后续的机器人视觉应用奠定坚实基础。

sunny的博客 648

Anaconda详细安装及使用教程(带图文)

Anacond的介绍 Anaconda指的是一个开源的Python发行版本,其包含了conda、Python等180多个科学包及其依赖项。因为包含了大量的科学包,Anaconda的下载文件比较大(约531 MB),如果只需要某些包,或者需要节省带宽或存储空间,也可以使用Miniconda这个较小的发行版(仅包含conda和Python)。 Conda是一个开源的包、环境管理器,可以用于...

代码帮 186万+

初步了解Panda3D场景管理

panda3d引擎中,所有对象抽象为节点;由节点构成树进行渲染;

bcbobo21cn的专栏 1100

算法面试准备 - 手撕系列第五期 - 单头注意力机制(包括Self_atten和Cross_atten)

算法面试准备 - 手撕系列第五期 - 单头注意力机制(包括Self_atten和Cross_atten)

m0_62030579的博客 3608

Pandas与ChatGPT的超强结合,爆赞!

ChatGPT、Pandas是强大的工具,当它们结合在一起时,可以彻底改变我们与数据交互和分析的方式。ChatGPT凭借其先进的自然语言处理能力,可以更直观地与数据进行类似人类的交互。而PandasAI可以增强Pandas数据分析体验。通过将复杂的数据操作任务转换为简单的自然语言查询,PandasAI使用户更容易从数据中提取有价值的见解,而无需编写大量代码。这对于那些还不熟悉Python或pandas操作/转换的人来说是一种编程的新方法。

m0_48891301的博客 665

Alphafold2/multimer Conda环境配置与GPU加速优化指南

本文详细介绍了如何在本地服务器或工作站上,通过Conda环境配置并优化GPU加速来部署Alphafold2及其多聚体版本Alphafold2-multimer。内容涵盖从硬件准备、依赖安装、数据库部署到实战预测与常见报错处理的全流程,重点解决了本地安装过程中的依赖冲突与GPU调用失败等关键问题,帮助研究人员高效运行这一蛋白质结构预测工具。

neovim7hacker的博客 470

Autosar软件组件分析及ARXML文件分析

Autosar软件组件分析及ARXML文件分析

专注汽车软件开发、AutoSAR、车载以太网、SOA、EE架构。 3604

python pandas

import pandas as pd data=pd.read_csv(csv_path,header=None) print data.values #print current data1=data.values data1[1,6]='aaa' print data1 #print again pd.DataFrame(data1).to_csv(saveto_csv_path,head

。橙子(Chengs)的博客 888

初探802.11协议(6)——Wi-Fi 6新特性简介

Wi-Fi 6新机制(特性)介绍

FanFF的博客 1523

Python库pandas下载、安装、配置、用法、入门教程 —— `read_csv()`用法详解

read_csv()使用namesdf = pd.read_csv("example.csv", names=["编号", "姓名", "年龄"])通过本文的学习,我们从Pandas安装开始,深入了解了read_csv()函数的基本和高级用法。无论是基础参数,还是处理缺失值与分块读取的技巧,都能帮助你在数据分析中快速上手。如果你对本文内容有任何疑问,或者想了解更多的Python和Pandas知识,欢迎添加我的微信,让我们一起学习和进步!

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Python库pandas下载、安装、配置、用法、入门教程 —— read_csv()用法详解

如果你觉得这篇文章对你有所帮助,欢迎分享给你的朋友或在社交媒体上推荐!Python库pandas下载、安装、配置、用法、入门教程 —— read_csv()用法详解。Python库pandas下载、安装、配置、用法、入门教程 —— read_csv()用法详解。后续可以结合真实数据,按照自己的分析需求选择合适的参数进行实验,进一步深化理解。如果你正在学习数据分析、机器学习或深度学习,pandas 是不可或缺的工具之一!,都将带你快速上手,轻松解决日常开发中的数据处理难题!这个强大的数据处理库。

猫头虎技术团队:授渔优于赠鱼,兴趣引领智慧,探索之乐尤显珍贵。商务合作+:Libin9iOak ,万粉变现+:优快云WF,猫头虎承诺每年免费为100名C站创作者做账号流量诊断服务!全网搜:猫头虎技术团队,点击文章底部名片或直接私信我一切皆可谈,快找虎哥! 2725

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

猫头虎分享:Python库 Pandas 的简介、安装、用法详解入门教程

Pandas是一个用于高效处理结构化数据的Python库,特别适合处理表格数据(类似Excel中的表格),比如金融数据、实验记录等。它提供了DataFrame和Series两大核心数据结构,能够帮助我们轻松应对大规模数据的导入、清洗、处理与分析工作。操作命令解释安装Pandas安装Pandas库读取CSV文件读取CSV文件创建DataFrame使用字典创建DataFrame数据筛选df[df['年龄'] > 25]根据条件筛选数据处理缺失值填充缺失值删除重复行删除重复行数据可视化。

猫头虎技术团队:授渔优于赠鱼,兴趣引领智慧,探索之乐尤显珍贵。商务合作+:Libin9iOak ,万粉变现+:优快云WF,猫头虎承诺每年免费为100名C站创作者做账号流量诊断服务!全网搜:猫头虎技术团队,点击文章底部名片或直接私信我一切皆可谈,快找虎哥! 1万+

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

pandas用法-详解教程

pandas用法-详解教程

qq_27480007的博客 2317

‍ 猫头虎 分享:Python库 Pandas 的简介、安装、用法详解入门教程

Pandas是一个开源的Python库,主要用于数据操作和分析。Series:一维标签化数组,可以保存不同类型的数据。DataFrame:二维标签化的数据结构,类似于电子表格或SQL表。Pandas简化了数据清洗、转换、分析和可视化的过程,使得处理复杂数据变得更加直观和高效。🐼✨功能方法说明读取CSV从CSV文件读取数据写入CSV将DataFrame写入CSV文件过滤数据df[条件]根据条件筛选数据排序数据根据指定列排序数据分组与聚合对数据进行分组并计算平均值数据类型转换。

猫头虎:授渔优于赠鱼,兴趣引领智慧,探索之乐尤显珍贵。商务合作+:Libin9iOak ,万粉变现+:优快云WF,猫头虎承诺每年免费为100名C站创作者做账号流量诊断服务! 1774

Pandas用法-详细教程

Pandas是Python的核心数据分析库,提供高效的数据结构和数据处理工具。

weixin_60876938的博客 729

Pandas高级教程之:GroupBy用法

pandas中的DF数据类型可以像数据库表格一样进行groupby操作。通常来说groupby操作可以分为三部分:分割数据,应用变换和和合并数据。

程序那些事 8908

Pandas教程 | 超好用的Groupby用法详解

在日常的数据分析中,经常需要将数据根据某个(多个)字段划分为不同的群体(group)进行分析,如电商领域将全国的总销售额根据省份进行划分,分析各省销售额的变化情况,社交领域将用户根据画像(性别、年龄)进行细分,研究用户的使用情况和偏好等。在Pandas中,上述的数据处理操作主要运用groupby完成,这篇文章就介绍一下groupby的基本原理及对应的agg、transform和apply操作。 为了后续图解的方便,采用模拟生成的10个样本数据,代码和数据如下: company=["A","B","C"

乌贼君的博客 3555
上一篇: NumPy教程(Numpy基本操作、Numpy数据处理)
下一篇: Matplotlib教程(Matplotlib基本用法)
YL_python_C++_java
博客等级 码龄7年 1392粉丝 142原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值