Python 数据分析 - Pandas

目录

Pandas

Series

索引、切片

索引

布尔索引

切片

操作

删除

计算

Series和矢量(数值)的运算

Series和Series的运算

数学函数

DataFrame

索引、切片

操作

添加新的列

添加新的行

删除列

删除行

更改行/列标签

将索引改为DataFrame中某个列

检测和处理NaN值

检测NaN值

处理NaN值

Pandas DataFrame中处理CSV文件

将CSV文件加载到Pandas DataFrame中

查看部分数据

检查NaN值

查看统计信息

对数据分组


Pandas

Pandas是Python 中的数据操纵和分析软件包。名称“Pandas”得名自计量经济学 Panel Data(面板数据)一词。
Pandas为Python带来了两个新的数据结构,即Pandas Series和Pandas DataFrame。借助这两个数据结构,我们能够轻松直观地处理带标签数据和关系数据。

机器学习的重要一步是首先检查数据,通过进行一些基本的数据分析,确保数据很适合你的训练算法。对于数据来说,数量并不是唯一重要的方面,数据质量也同等重要。经常大型数据库并不能直接馈送到学习算法中,很多时候存在大型数据集缺失值、离群值、不正确的值,等等。这时候,Pandas 就派上用场了。Pandas Series 和 DataFrame 专门用于快速进行数据分析和操纵。

 

Series

A Pandas Series is a one-dimensional array-like object that can hold many data types and you can assign an index label to each element in the Pandas Series.

带索引的一维数组,有两个属性,values和index。
1. 默认情况下,创建一个Series时,会自动添加数字形式的索引

import pandas as pd

s = pd.Series(["a","b","c"])
print(s)
print(type(s))
print(s.values, s.index)
print(s.ndim, s.shape, s.size)
0    a
1    b
2    c
dtype: object
<class 'pandas.core.series.Series'>
['a' 'b' 'c'] RangeIndex(start=0, stop=3, step=1)
1 (3,) 3
[Finished in 0.5s]

2. 可以加入index参数来指定索引

import pandas as pd
import numpy as np

s = pd.Series(["a","b","c"], index=[0,1,2])
print(s)
print(type(s))
print(s.values, s.index)
print(s.ndim, s.shape, s.size)

print("*********")

s = pd.Series(["a","b","c"], index=[1,2,3])
print(s)
print(type(s))
print(s.values, s.index)
print(s.ndim, s.shape, s.size)

print("*********")

s = pd.Series(np.arange(3), index=["a","b","c"])
print(s)
print(type(s))
print(s.values, s.index)
print(s.ndim, s.shape, s.size)
0    a
1    b
2    c
dtype: object
<class 'pandas.core.series.Series'>
['a' 'b' 'c'] Int64Index([0, 1, 2], dtype='int64')
1 (3,) 3
*********
1    a
2    b
3    c
dtype: object
<class 'pandas.core.series.Series'>
['a' 'b' 'c'] Int64Index([1, 2, 3], dtype='int64')
1 (3,) 3
*********
a    0
b    1
c    2
dtype: int64
<class 'pandas.core.series.Series'>
[0 1 2] Index(['a', 'b', 'c'], dtype='object')
1 (3,) 3
[Finished in 0.4s]

3. 可以使用字典创建Series:
如果没有使用index参数,Series的index - 字典的key,Series的values - 字典的value;
如果使用了index参数,Series的index - 以index参数为准,如果字典中没有该key,values为NaN(Not a Number)

import pandas as pd

data = {"test1score":80, "test2score":70}
print(data, "\n")

s = pd.Series(data)
print(s)
print(type(s))
print(s.values, s.index)
print(s.ndim, s.shape, s.size)

print()

s = pd.Series(data, index=["test1score", "test3score"])
print(s)
print(type(s))
print(s.values, s.index)
print(s.ndim, s.shape, s.size)
{'test1score': 80, 'test2score': 70} 

test1score    80
test2score    70
dtype: int64
<class 'pandas.core.series.Series'>
[80 70] Index(['test1score', 'test2score'], dtype='object')
1 (2,) 2

test1score    80.0
test3score     NaN
dtype: float64
<class 'pandas.core.series.Series'>
[80. nan] Index(['test1score', 'test3score'], dtype='object')
1 (2,) 2
[Finished in 0.4s]

eg.

import pandas as pd

# We create a Pandas Series that stores a grocery list
groceries = pd.Series(data=[30, 6, 'Yes', 'No'], index=['eggs', 'apples', 'milk', 'bread'])
print(groceries)

x1 = 'bananas' in groceries.index
x2 = 'bananas' in groceries
print('Is bananas an index label in Groceries:', x1)
print('Is bananas an index label in Groceries:', x2)

y1 = 'bread' in groceries.index
y2 = 'bread' in groceries
print('Is bread an index label in Groceries:', y1)
print('Is bread an index label in Groceries:', y2)

u = 'No' in groceries.values
print("Is 'No' a value in Groceries:", u)

v = 60 in groceries.values
print('Is 60 a value in Groceries:', v)
eggs       30
apples      6
milk      Yes
bread      No
dtype: object
Is bananas an index label in Groceries: False
Is bananas an index label in Groceries: False
Is bread an index label in Groceries: True
Is bread an index label in Groceries: True
Is 'No' a value in Groceries: True
Is 60 a value in Groceries: False
[Finished in 0.4s]

索引、切片

索引

1. access elements using index labels/numerical indices

在方括号[]内添加索引标签或数字索引访问元素。使用数字索引时,使用正整数从Series的开头访问数据,或使用负整数从末尾访问。

Pandas Series 提供了两个属性 .loc 和 .iloc。属性 .loc 表示位置,用于明确表明我们使用的是标签索引。\属性.iloc 表示整型位置,用于明确表明我们使用的是数字索引。

2. 通过索引获取多个值

import pandas as pd

groceries = pd.Series(data=[30, 6, 'Yes', 'No'], index=['eggs', 'apples', 'milk', 'bread'])
print(groceries)

print()

print('How many eggs do we need to buy:', groceries['eggs'])
print('How many eggs do we need to buy:', groceries.loc['eggs'])
print('How many eggs do we need to buy:', groceries[0])
print('How many eggs do we need to buy:', groceries.iloc[0])

print()

print('Do we need milk and bread:', groceries[['milk','bread']].values)
print('Do we need milk and bread:', groceries.loc[['milk','bread']].values)
print('Do we need milk and bread:', groceries[[-2,-1]].values)
print('Do we need milk and bread:', groceries.iloc[[-2,-1]].values)
print('Do we need milk and bread:\n{}'.format(groceries[['milk','bread']]))
eggs       30
apples      6
milk      Yes
bread      No
dtype: object

How many eggs do we need to buy: 30
How many eggs do we need to buy: 30
How many eggs do we need to buy: 30
How many eggs do we need to buy: 30

Do we need milk and bread: ['Yes' 'No']
Do we need milk and bread: ['Yes' 'No']
Do we need milk and bread: ['Yes' 'No']
Do we need milk and bread: ['Yes' 'No']
Do we need milk and bread:
milk     Yes
bread     No
dtype: object
[Finished in 0.5s]

3. 通过索引对Series的values进行修改

4. (基于2、3)通过多个索引进行赋值操作

import pandas as pd

s = pd.Series(data=[1,2,3,4,5], index=["a","b","c","d","e"])
print(s)

print(s["a"])
s["a"] = 9
print(s)

print(s[["b","d","e"]])
s[["b","d","e"]] = [s["d"],s["e"],s["b"]]
print(s)
s[["b","d","e"]] = 0
print(s)

print("*********")

data = {"test1score":80, "test2score":70}
s = pd.Series(data, index=["test1score","test2score","test3score"])
print(s)
print(s[["test1score","test3score"]])
a    1
b    2
c    3
d    4
e    5
dtype: int64
1
a    9
b    2
c    3
d    4
e    5
dtype: int64
b    2
d    4
e    5
dtype: int64
a    9
b    4
c    3
d    5
e    2
dtype: int64
a    9
b    0
c    3
d    0
e    0
dtype: int64
*********
test1score    80.0
test2score    70.0
test3score     NaN
dtype: float64
test1score    80.0
test3score     NaN
dtype: float64
[Finished in 0.5s]

布尔索引

pandas.isnull()获取Series中values为空的值,pandas.notnull()获取Series中values不为空的值

import pandas as pd

s = pd.Series(data=[1,2,3,4,5], index=["a","b","c","d","e"])
print(s)

print(s>2)
print(s[s>2])
s[s>2] = -1
print(s)

print("*********")

data = {"test1score":80, "test2score":70}
s = pd.Series(data, index=["test1score","test2score","test3score"])
print(s)

print(pd.isnull(s))
print(s[pd.isnull(s)])
print(s[pd.notnull(s)])
s[pd.isnull(s)] = 0
print(s)
a    1
b    2
c    3
d    4
e    5
dtype: int64
a    False
b    False
c     True
d     True
e     True
dtype: bool
c    3
d    4
e    5
dtype: int64
a    1
b    2
c   -1
d   -1
e   -1
dtype: int64
*********
test1score    80.0
test2score    70.0
test3score     NaN
dtype: float64
test1score    False
test2score    False
test3score     True
dtype: bool
test3score   NaN
dtype: float64
test1score    80.0
test2score    70.0
dtype: float64
test1score    80.0
test2score    70.0
test3score     0.0
dtype: float64
[Finished in 0.4s]

切片

1. = 为引用传递,并不是值传递
2. copy函数,在堆中再创建内容相同的一份

import pandas as pd

s = pd.Series([1,2,3,4,5], index=["a","b","c","d","e"])
print('s:\n{}'.format(s))
s2 = s[1:4]
print('s2:\n{}'.format(s2))
s2[0:2] = [9,8]
print('s2:\n{}'.format(s2))
print('s:\n{}'.format(s))

print()

s = pd.Series([1,2,3,4,5], index=["a","b","c","d","e"])
print('s:\n{}'.format(s))
s3 = s[1:4].copy()
print('s3:\n{}'.format(s3))
s3[0:2] = [9,8]
print('s3:\n{}'.format(s3))
print('s:\n{}'.format(s))
s:
a    1
b    2
c    3
d    4
e    5
dtype: int64
s2:
b    2
c    3
d    4
dtype: int64
s2:
b    9
c    8
d    4
dtype: int64
s:
a    1
b    9
c    8
d    4
e    5
dtype: int64

s:
a    1
b    2
c    3
d    4
e    5
dtype: int64
s3:
b    2
c    3
d    4
dtype: int64
s3:
b    9
c    8
d    4
dtype: int64
s:
a    1
b    2
c    3
d    4
e    5
dtype: int64
[Finished in 0.5s]

 

操作

删除

Series.drop(label):从给定 Series 中删除给定的 label,不在原地地从 Series 中删除元素,即不会更改被修改的原始 Series。
Series.drop(label, inplace=True):从给定 Series 中删除给定的 label,原地地从 Pandas Series 中删除条目。

import pandas as pd

# We create a Pandas Series that stores a grocery list
groceries = pd.Series(data=[30, 6, 'Yes', 'No'], index=['eggs', 'apples', 'milk', 'bread'])
print('Original Grocery List:\n{}'.format(groceries))

# We remove apples from our grocery list. The drop function removes elements out of place
print("We remove apples by groceries.drop('apples'):\n{}".format(groceries.drop('apples')))
# When we remove elements out of place the original Series remains intact.
print('Modified Grocery List:\n{}'.format(groceries))

# We remove apples from our grocery list in place by setting the inplace keyword to True
print("We remove apples by groceries.drop('apples', inplace=True):\n{}".format(groceries.drop('apples', inplace=True)))
print('Modified Grocery List:\n{}'.format(groceries))
Original Grocery List:
eggs       30
apples      6
milk      Yes
bread      No
dtype: object
We remove apples by groceries.drop('apples'):
eggs      30
milk     Yes
bread     No
dtype: object
Modified Grocery List:
eggs       30
apples      6
milk      Yes
bread      No
dtype: object
We remove apples by groceries.drop('apples', inplace=True):
None
Modified Grocery List:
eggs      30
milk     Yes
bread     No
dtype: object
[Finished in 0.5s]

 

计算

Series和矢量(数值)的运算

Series的每一个values和数值进行计算

import pandas as pd

# We create a Pandas Series that stores a grocery list of just fruits
fruits = pd.Series(data=[10,6,3], index=['apples','oranges','bananas'])
print('Original grocery list of fruits:\n{}'.format(fruits))

# We perform basic element-wise operations using arithmetic symbols
print('\nfruits + 10:\n{}'.format(fruits + 10)) # We add 10 to each item in fruits
print('\nfruits - 10:\n{}'.format(fruits - 10)) # We subtract 10 to each item in fruits
print('\nfruits * 10:\n{}'.format(fruits * 10)) # We multiply each item in fruits by 10 
print('\nfruits / 10:\n{}'.format(fruits / 10)) # We divide each item in fruits by 10
Original grocery list of fruits:
apples     10
oranges     6
bananas     3
dtype: int64

fruits + 10:
apples     20
oranges    16
bananas    13
dtype: int64

fruits - 10:
apples     0
oranges   -4
bananas   -7
dtype: int64

fruits * 10:
apples     100
oranges     60
bananas     30
dtype: int64

fruits / 10:
apples     1.0
oranges    0.6
bananas    0.3
dtype: float64
[Finished in 0.4s]
import pandas as pd

# We create a Pandas Series that stores a grocery list
groceries = pd.Series(data=[30, 6, 'Yes', 'No'], index=['eggs', 'apples', 'milk', 'bread'])
print('Original Grocery List:\n{}'.format(groceries))
# We multiply our grocery list by 2
print('\nWe multiply our grocery list by 2:\n{}'.format(groceries * 2))
Original Grocery List:
eggs       30
apples      6
milk      Yes
bread      No
dtype: object

We multiply our grocery list by 2:
eggs          60
apples        12
milk      YesYes
bread       NoNo
dtype: object
[Finished in 0.4s]

Series和Series的运算

前提是要有相同的index,对应index的values进行计算

import pandas as pd

data1 = {"Jack": 92, "James": 59, "Jane": 60, "Jennifer": 70, "Jill": 80}
data2 = {"Jack": 79, "James": 64, "Jane": 75, "Janet": 50, "Jill": 83}
print(data1)
print(data2)

print()

s1 = pd.Series(data1)
s2 = pd.Series(data2)
print(s1)
print(s2)
print(s1 + s2)

print()

s1 = pd.Series(data1, index=["Jane", "Jill", "Jack", "James"])
s2 = pd.Series(data2, index=["Jill", "Jane", "James", "Jack"])
print(s1)
print(s2)
print(s1 + s2)
{'Jack': 92, 'James': 59, 'Jane': 60, 'Jennifer': 70, 'Jill': 80}
{'Jack': 79, 'James': 64, 'Jane': 75, 'Janet': 50, 'Jill': 83}

Jack        92
James       59
Jane        60
Jennifer    70
Jill        80
dtype: int64
Jack     79
James    64
Jane     75
Janet    50
Jill     83
dtype: int64
Jack        171.0
James       123.0
Jane        135.0
Janet         NaN
Jennifer      NaN
Jill        163.0
dtype: float64

Jane     60
Jill     80
Jack     92
James    59
dtype: int64
Jill     83
Jane     75
James    64
Jack     79
dtype: int64
Jack     171
James    123
Jane     135
Jill     163
dtype: int64
[Finished in 0.5s]

 

数学函数

import pandas as pd

# We create a Pandas Series that stores a grocery list of just fruits
fruits = pd.Series(data=[10,6,3], index=['apples','oranges','bananas'])
print('Original grocery list of fruits:\n{}'.format(fruits))

# We import NumPy as np to be able to use the mathematical functions
import numpy as np
# We apply different mathematical functions to all elements of fruits
print('\nEXP(X) = \n{}'.format(np.exp(fruits)))
print('\nSQRT(X) =\n{}'.format(np.sqrt(fruits)))
print('\nPOWER(X,2) =\n{}'.format(np.power(fruits,2)))
Original grocery list of fruits:
apples     10
oranges     6
bananas     3
dtype: int64

EXP(X) = 
apples     22026.465795
oranges      403.428793
bananas       20.085537
dtype: float64

SQRT(X) =
apples     3.162278
oranges    2.449490
bananas    1.732051
dtype: float64

POWER(X,2) =
apples     100
oranges     36
bananas      9
dtype: int64
[Finished in 0.5s]

 

DataFrame

DataFrame is a two-dimensional object with labeled rows and columns and can also hold multiple data types.

二维表,往往使用SQL操作数据库达不到想要的结果时,才使用Python中的DataFrame。

结构化数据:excel表格(也是二维表),数据库的table
非结构化数据:文本、图片、视频
半结构化数据:xml文本

columns获取列名,info()获取每一列的信息,shape获取结构。

可以通过columns和index参数来指定列名和索引,如果columns参数指定的列在字典中没有匹配项,那么会保留该列名,值为NaN。

1. 通过a Dictionary创建Pandas DataFrame

1.1 通过a Dictionary of Pandas Series创建Pandas DataFrame

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python是一种功能强大的编程语言,可以用于各种数据分析任务。而在Python数据分析工具库中,pandas是最受欢迎和广泛使用的工具之一。 Pandas提供了用于处理和分析数据的高级数据结构和函数。其最常用的数据结构是DataFrame,类似于Excel中的表格。通过Pandas,我们可以读取Excel文件,并将其转换为DataFrame对象进行进一步处理。 使用Pandas进行Excel数据分析的第一步是读取Excel文件。Pandas提供了read_excel函数,可以方便地读取Excel文件并转换为DataFrame对象。我们可以指定要读取的工作表、要保留的列、要跳过的行等。 一旦我们将Excel文件读取为DataFrame对象,我们可以使用Pandas提供的丰富函数和操作对数据进行各种处理和分析。例如,我们可以使用head()函数查看前几行数据,使用describe()函数获取数据的统计摘要,使用mean()函数计算平均值,使用groupby()函数对数据进行分组等等。 除了数据处理和分析,Pandas还提供了各种工具来处理缺失值和数据清洗。我们可以使用dropna()函数删除含有缺失值的行或列,使用fillna()函数将缺失值填充为指定的值,使用replace()函数替换数据中的特定值等。 在数据分析完成后,我们可以使用to_excel函数将DataFrame对象保存为Excel文件。在保存时,我们可以指定要保存的工作表、保存的位置和文件名等。 总之,Pandas是一个非常强大和灵活的库,可以使Python在处理Excel数据时变得更加简单和高效。无论是数据的读取、处理、分析还是保存,Pandas都提供了丰富而简洁的函数和操作,使得数据分析变得更加容易。 ### 回答2: Pandas是一个功能强大的数据分析工具,可以轻松地处理和分析各种数据。同时,Pandas还提供了许多用于读取、处理和写入Excel文件的功能,让我们能够更方便地从Excel文件中提取和处理数据。 在使用Pandas进行Excel数据分析时,我们首先需要使用`pandas.read_excel()`函数读取Excel文件,并将其存储为一个Pandas的DataFrame对象。这样可以轻松地使用Pandas的各种数据处理和分析功能。 Pandas提供了一系列的函数来处理Excel数据,比如对数据进行过滤、排序、计算统计量等。我们可以使用`head()`函数快速查看数据的前几行,使用`describe()`函数生成数据的统计概要信息,使用`sort_values()`函数对数据进行排序等。 除此之外,Pandas还提供了一些方便的函数来进行Excel数据的写入。我们可以使用`to_excel()`函数将DataFrame对象写入Excel文件,并通过参数来设置写入的Sheet名称、行列标签等。 除了基本的读写操作,Pandas还提供了丰富的数据转换和清洗功能,如数据合并、去重、填充空值等等。这些功能可以帮助我们更好地理解和分析Excel中的数据。 总而言之,Pandas是一个非常方便和强大的数据分析工具,可以让我们轻松地处理和分析Excel数据。通过Pandas,我们可以更加快速和高效地提取、清洗和分析数据,将Excel文件作为数据分析的重要来源之一。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值