Python数据分析摘要(1)- DataFrame数据定位,筛选和修改

数据分析在社会和经济生活中扮演着越来越重要的角色。因此,我在接下的几篇blog中阐释比较常用的数据分析的代码,如有不妥,欢迎指正!
数据分析第一个常用的库是pandas。 相比较numpy和matplotlib, 在产生相同效果的同时,pandas 体现出强大的API 功能,获取数据的途径更加便捷,所以备受推崇。
首先,我们来了解一下 pandas 中 DataFrame这个类的一些基本情况。DataFrame来源于R语言的data.frame类,因此自身功能多样。
其次,介绍一下DataFrame对象的数据定位和赋值方法。

常见注释符号说明:<> 里面是变量,args; op 代指operator,逻辑运算符。

一. DataFrame对象的数据定位
(1) 方法一: pandas.DataFrame().loc[]方法 【基本逻辑:先index后column】index指的是行索引,column则为列。

首先建立一个DataFrame对象,

import pandas as pd
import numpy as np

df = pd.DataFrame([[1,2,3,4],[3,4,3,4],[5,6,7,8]], index= ['number','post','ID'], columns = ['a','b','c','d'])
print(df)

得到结果如下

        a  b  c  d
number  1  2  3  4
post    3  4  3  4
ID      5  6  7  8

应用一:利用loc[]方法,得到某一个tuple(tupel可以理解为行数据)
如:

print(df.loc['number'])

得到结果如下

a    1
b    2
c    3
d    4

应用二:获取某些index,把index写到一个list中;利用loc[[,]]方法,得到某些tuple

print(df.loc[['number', 'post']])

得到结果如下

        a  b  c  d
number  1  2  3  4
post    3  4  3  4

应用三:获取某些index,把index写到一个list中,同时利用切片方法;利用loc[:]切片方法,得到某些tuple

print(df.loc['number':'ID'])

得到结果如下

        a  b  c  d
number  1  2  3  4
post    3  4  3  4
ID      5  6  7  8

应用三拓展:类似应用三,利用loc[:, [,]]切片方法,得到某些满足index和column条件的tuple

print(df.loc['number':'ID',['a','c']])

得到结果如下

        a  c
number  1  3
post    3  3
ID      5  7

应用四:利用loc[df[] op] 对满足column条件的tuple进行筛选

print(df.loc[df['b']>2,['c','a']])

得到结果如下

      c  a
post  3  3
ID    7  5

应用四拓展:利用loc[lambda函数方程] 对满足column条件的tuple进行筛选,注意lambda后面的变量为DataFrame对象

print(df.loc[lambda x: x.a >3,:])

得到结果如下

    a  b  c  d
ID  5  6  7  8

(2) 方法二: pandas.DataFrame().iloc[]方法 【基本逻辑:先index后column, 但iloc内部输入的是数值,而不是索引】
iloc[] 与 loc[] 的应用极其相似,以上四个应用方法完全对变量args的处理完全相同。

这里我只列举一个取前2行,第2列的例子:

print(df.iloc[:2,1])

得到结果如下

number    2
post      4

(3) 方法三: pandas.DataFrame()[]方法 【基本逻辑: 根据列名(attribute)直接取满足列要求的tuple数据】

print(df[['a','c']])

得到结果如下

        a  c
number  1  3
post    3  3
ID      5  7

二. DataFrame对象的数据修改 【基本逻辑: 先定位,再赋值

下边举一个简单例子:把index为number的行数值转化为-1, 同时对attribute(列名)为a的所有大于0的tuple(行数据)赋值为-2。

df.loc['number'] = -1
df.loc[df['a']>0] =-2
print(df)

得到结果如下

        a  b  c  d
number -1 -1 -1 -1
post   -2 -2 -2 -2
ID     -2 -2 -2 -2

三. DataFrame对象的apply方法应用 【基本逻辑: 对每行/每列做函数运算】
方法参数:apply(func,
axis=0是对每列/axis=1是对每行,
raw=False默认为Series类型/raw=True是ndarray类型,
result_type=None, args=())

最后举个栗子帮助大家理解:
对每行元素做累加运算,最后得到一列。

代码如下:

print(df.apply(np.sum, axis = 1))

得到结果如下

number    10
post      14
ID        26

写在最后,今天的总结就到这里;如果觉得有帮助,请点个赞!

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Efred.D

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值