Python中的pandas库

1.用pandas打开.csv或者.xlsx文件
.csv文件是以","作为分隔符的文件,可以用Excel打开(2003或者2007)

from pandas import *

fp = DataFrame(read_csv('food_info.csv')) #打开.csv文件
print(fp.head(1)) #打印数据的头1行,fp.tail(3) #打印数据的最后3行
print(fp.shape)

在这里插入图片描述

df = pd.DataFrame(pd.read_excel('name.xlsx')) #打开.文件xlsx

2.打印行信息

from pandas import *

fp = DataFrame(read_csv('food_info.csv'))
print(fp.loc[0]) #打印第0行
print(fp.loc[0:3]) #打印0-3行,这和python不一样,python中[0:3]左包右不包
print(fp.loc[[2,5,6,8,9]]) #打印2,5,6,8,9行

3.打印列信息

from pandas import *

fp = DataFrame(read_csv('food_info.csv'))
print(fp.columns.tolist()) #打印列名,并转化为列表形式
print(fp["NDB_No"]) #打印列名为NDB_No这一列
print(fp[["NDB_No","Water_(g)","Sugar_Tot_(g)"]])#打印列名为NDB_No,Water_(g),Sugar_Tot_(g)这3列

4.小练习:查找数据中列是以(g)为单位的

from pandas import *

fp = DataFrame(read_csv('food_info.csv'))

col_names = fp.columns.tolist()
print(col_names) #打印列名,并转化为列表形式

#查找哪些列单位是(g)为结尾
columns_g = [] #存储列名

for name in col_names:
    if name.endswith("(g)"): #如果name是以(g)为结尾
        columns_g.append(name)
fp_g = fp[columns_g]
print(fp_g)

5.数据的简单运算

from pandas import *

fp = DataFrame(read_csv('food_info.csv'))
Water_kg = fp['Water_(g)'] / 1000 #将Water_(g)这一列的数据转换成以kg为单位
print(Water_kg)
from pandas import *

fp = DataFrame(read_csv('food_info.csv'))
water_energy = fp["Water_(g)"] * fp["Energ_Kcal"] #将两个列的数据对应相乘
print(water_energy)

6.添加一列(保证数据的维度是一样的)

from pandas import *

fp = DataFrame(read_csv('food_info.csv'))
print(fp.shape) #打印原始数据的列数

water_energy = fp["Water_(g)"] * fp["Energ_Kcal"]
#print(water_energy)
fp["Water_Energy"] = water_energy #新增一列(列名为"Water_Energy"),且数据的维度是与原数据一致
print(fp.shape) #对比之前的36列,现在打印出来是37列

结果是:
在这里插入图片描述
7.排序

from pandas import *

fp = DataFrame(read_csv('food_info.csv'))
fp.sort_values("Water_(g)",inplace=True,ascending=False) #inplace表示直接在原数据上排序,降序
print(fp["Water_(g)"]) #结果是降序排序

部分结果:
在这里插入图片描述
可以看到排序的结果第1列的索引值还是乱的,可以在新数据上面调用.reset_index()

from pandas import *

fp = DataFrame(read_csv('food_info.csv'))
fp.sort_values("Water_(g)",inplace=True,ascending=False) #inplace表示直接在原数据上排序,降序
#print(fp["Water_(g)"]) #结果是降序排序
fp_reindexed = fp.reset_index(drop=True) #drop=True表示重新新的数据
print(fp_reindexed["Water_(g)"][0:10])

在这里插入图片描述

8.缺失值的处理

#找出缺失值
from pandas import *
from numpy import *

fp = DataFrame(read_csv("titanic_train.csv"))

age = fp["Age"]

AgeIsNull = isnull(age)
print(AgeIsNull) #打印结果是False True 其中NaN的位置为False
print(age[AgeIsNull]) #打印age列中为NaN的

9.小练习:计算每个船舱的平均价位

from pandas import *
from numpy import *

fp = DataFrame(read_csv("titanic_train.csv"))

ship_class = [1,2,3]
fare_dict = {}

for this_class in ship_class:
    pclass_rows = fp[fp["Pclass"]==this_class] #this_class的数据
    pclass_fares = pclass_rows["Fare"] #把this_class数据的Fare列对应的值取出来
    fare_class_mean = pclass_fares.mean() #求平均值,这里是直接把带有NaN的数据丢弃
    fare_dict[this_class] = fare_class_mean #给字典赋值

print(fare_dict) #打印:{1: 84.1546875, 2: 20.662183152173913, 3: 13.675550101832993}

10.上面9.的程序还是相对来说比较复杂,pandas.pivot_table可以轻松处理,就相当于数据透视表一样

from pandas import *
from numpy import *

fp = DataFrame(read_csv("titanic_train.csv"))

passenger_survival = fp.pivot_table(index="Pclass",values="Survived",aggfunc=mean)
#index是根据index来分类,values是计算这列的数据(可以多列["","",..]),aggfunc是计算的函数
print(passenger_survival)

在这里插入图片描述
11.pandas.dropna()丢弃具有缺失值的整条数据

from pandas import *
from numpy import *

fp = DataFrame(read_csv("titanic_train.csv"))
print(fp.shape) #(891, 12)

dropna_col = fp.dropna(axis=0,subset=["Age","Sex"]) #将"Age","Sex"中有缺失值的数据丢弃

print(dropna_col.shape) #(714, 12)

12.数据定位到具体的位置

from pandas import *
from numpy import *

fp = DataFrame(read_csv("titanic_train.csv"))

age_84 = fp.loc[84,"Age"] #查看第84行数据的年龄
print(age_84) #17.0

13.pandas.apply()应用函数:自定义函数去应用

from pandas import *
from numpy import *

def hundreth_row(column): #自定义的函数
    hundreth_item = column.loc[99]
    return hundreth_item

fp = DataFrame(read_csv("titanic_train.csv"))

hundreth_row = fp.apply(hundreth_row) #apply应用函数
print(hundreth_row) #打印出第100行数据的信息

14.series

from pandas import *
from numpy import *

fp = DataFrame(read_csv("fandango_score_comparison.csv"))

series_film = fp["FILM"]
print(type(series_film)) #<class 'pandas.core.series.Series'>
print(series_film[0:5])
series_rt = fp["RottenTomatoes"] #RottenTomatoes列是这个媒体的评分值
print(series_rt[0:5])

film_names = series_film.values #FILE列所有的数据
print(type(film_names)) #<class 'numpy.ndarray'>

rt_scores = series_rt.values #"RottenTomatoes"列所有的数据
series_custom = Series(rt_scores,index=film_names)
print(series_custom[["Minions (2015)","Leviathan (2014)"]])

15.pd.value_counts(data['Class'])
计算数据集Class列所有属性对应的数据的个数,可以检查样本是否均衡
☆持续更新

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值