Datawha组队——Pandas(下)综合练习(打卡)

import pandas as pd
import numpy as np
import missingno as msno
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号#读取数据
df = pd.read_csv('端午粽子数据.csv')
df.columns = df.columns.str.strip()
df.columns
print(msno.matrix(df))

df = df.drop(df.index[df['发货地址'].isnull()],axis=0)
# df_1 = df[df['发货地址'].str.contains(r'[杭州]{2}')]
def is_number(x):try:float(x)return Trueexcept (SyntaxError,ValueError) as e :return Falsedf[~df.价格.map(is_number)]
df.loc[[538,4376],'价格']=['45.9','45.0']
df['价格'] = df['价格'].astype(float)
df_1 = df[df['发货地址'].str.contains(r'[杭州]{2}')]
df_1['价格'].mean()

结果为:

df[df['标题'].str.contains(r'[嘉兴]{2}') & ~(df['发货地址'].str.contains(r'[嘉兴]{2}'))]

df['价格'].describe(percentiles=[.2,.4,.6,.8]).loc[['20%','40%','60%','80%']]
df['new_价格'] = pd.cut(df['价格'],[0.0,29.3,43.9,69.84,124.80,np.inf],labels=['低','较低','中','较高','高'])
df.set_index('new_价格').sort_index(ascending=False).head()

df['new_付款人数'] = df['付款人数'].astype('string').str.extract(r'(\d+(\.\d+)?)')[0]
# df['new_付款人数_wan'] = df['付款人数'].astype('string').str.extract(r'(\d+\.?\d*\d+)',expand=False)
df['new_付款人数'] = pd.to_numeric(df['new_付款人数'],errors='coerce')
df['付款人数'] = df['付款人数'].apply(str)
s1 = pd.to_numeric((df[df['付款人数'].str.contains(r'[万]{1}')]['new_付款人数']*10000))
s2 = pd.to_numeric(df[~(df['付款人数'].str.contains(r'[万]{1}'))]['new_付款人数'])
df['new_付款人数']= pd.concat([s1,s2],axis=0)#查看缺失值数量
print(df['new_付款人数'].isnull().sum())
print(df.index[df['new_付款人数'].isnull()])
print(df.loc[183])
g = df.groupby(df['new_价格'])
# g.groups
print(g.get_group('低')['new_付款人数'].isnull().sum())
print(g.get_group('较低')['new_付款人数'].isnull().sum())
print(g.get_group('中')['new_付款人数'].isnull().sum())
print(g.get_group('较高')['new_付款人数'].isnull().sum())
print(g.get_group('高')['new_付款人数'].isnull().sum())#求均值
print(g.get_group('低')['new_付款人数'].mean())
print(g.get_group('较低')['new_付款人数'].mean())
print(g.get_group('中')['new_付款人数'].mean())
print(g.get_group('较高')['new_付款人数'].mean())
print(g.get_group('高')['new_付款人数'].mean())#缺失值填充
df['new_付款人数'].fillna(g.get_group('低')['new_付款人数'].mean(),inplace=True)
df['new_付款人数'].isnull().sum()

存在问题:通过之前对价格的分类对数据进行分类填充,但是在填充时,发现不能分组填充,只能一次性填充,这个问题待思考解决。

#字符串拼接
address = []
for i in df['发货地址'].str.split(' '):if len(i)>1:add = i[0]+i[1]else:add = i[0]address.append(add)
df['new_发货地址']= address
('商品发货地为'+df['new_发货地址']+',店铺为'+df['店铺']+',共计'+df['付款人数']+',单价为'+df['价格']).to_frame().rename(columns={0:'ID'})#apply函数
s = df.apply(lambda r:f'商品发货地址为{r["new_发货地址"]},店铺为{r["店铺"]},共计{r["付款人数"]},单价为{r["价格"]}',axis=1).to_frame().rename(columns={0:'ID'})
s

address = []
shops = []
persons = []
prices = []
for i in s['ID'].str.split(','):add = i[0].split('为')[1]if len(add)>3:add = add[:2] + ' ' + add[2:]shop = i[1].split('为')[1]person = i[2].split('计')[1]price  = i[3].split('为')[1]address.append(add)shops.append(shop)persons.append(person)prices.append(price)
s['发货地址'] = address
s['店铺'] = shops
s['付款人数'] = persons
s['价格'] = prices
print(s)

df = pd.read_csv('墨尔本温度数据.csv')
df

holiday = pd.date_range(start='19810501', end='19810503').append(pd.date_range(start='19820501', end='19820503')).append(pd.date_range(start='19830501', end='19830503')).append(pd.date_range(start='19840501', end='19840503')).append(pd.date_range(start='19850501', end='19850503')).append(pd.date_range(start='19860501', end='19860503')).append(pd.date_range(start='19870501', end='19870503')).append(pd.date_range(start='19880501', end='19880503')).append(pd.date_range(start='19890501', end='19890503')).append(pd.date_range(start='19900501', end='19900503')).append(pd.date_range(start='19811001', end='19811007')).append(pd.date_range(start='19821001', end='19821007')).append(pd.date_range(start='19831001', end='19831007')).append(pd.date_range(start='19841001', end='19841007')).append(pd.date_range(start='19851001', end='19851007')).append(pd.date_range(start='19861001', end='19861007')).append(pd.date_range(start='19871001', end='19871007')).append(pd.date_range(start='19881001', end='19881007')).append(pd.date_range(start='19891001', end='19891007')).append(pd.date_range(start='19891001', end='19891007')).append(pd.date_range(start='19810101', end='19901231',freq='BMS'))
holiday = holiday.drop_duplicates()
df['Date'] = pd.to_datetime(df['Date'])
result = df[~df['Date'].isin(holiday)].set_index('Date').resample('M').mean()
result

#常规法
years = []
months = []
for i in df['Date'].astype('string').str.split('-'):year = i[0]month = str(int(i[1]))years.append(year)months.append(month)
df['Y'] = years
df['M'] = months
Y = df.groupby('Y')
M = df.groupby(['Y','M'])
tempYlist = []
tempYZlist = []
for i in range(1981,1991):tempYlist = []for j in range(1,13):tempY = Y.get_group(str(i))[Y.get_group(str(i))['M']==str(j)]['Temp'].min()
#          print(tempY)tempYlist.append(tempY)Ymean = np.sum(np.mean(tempYlist))
tempMZlist = []
for i in range(1,13):tempMlist = []for j in range(1981,1991):tempM = Y.get_group(str(j))[Y.get_group(str(j))['M']==str(i)]['Temp'].min()tempMlist.append(tempM)print(tempMlist)tempMZlist.append(np.mean(tempMlist))
Sj = tempMZlist/Ymean
Sj

import pandas as pd
import numpy as np
import datetime 
df = pd.read_csv('摩拜单车数据.csv')
df['new_start_time'] = pd.to_datetime(df['start_time'] )
df['new_start_time'] = pd.to_datetime(df['new_start_time'].apply(lambda x:datetime.datetime.strftime(x,'%Y-%m-%d')))
# datetime.datetime.strftime(df['new_start_time'][0],'%Y-%m-%d')

df['start_time'] = pd.to_datetime(df['start_time'])
df['work_week'] = df['start_time'].dt.dayofweek
df.groupby('work_week').size()

对数据按星期分类,0-6代表星期一到星期天,统计每天的交易量

data = df.groupby('new_start_time')
zts = pd.Timestamp('2016-07-31 07:30')
zte = pd.to_datetime('2016-07-31 09:30')
wts = pd.to_datetime('2016-07-31 17:30')
wte = pd.to_datetime('2016-07-31 19:00')
time = pd.to_datetime('2016-07-31 00:00:00')
times = []
countZs = []
countWs = []
for i in range(1,32):zts = zts + pd.offsets.Day()zte = zte + pd.offsets.Day()wts = wts + pd.offsets.Day()wte = wte + pd.offsets.Day()time = datetime.datetime.strftime(time + pd.offsets.Day(),'%Y-%m-%d %H:%M:%S')countZ = data.get_group(time)[(data.get_group(time)['start_time']>= zts) & (data.get_group(time)['start_time']<= zte)]['start_time'].count()countW = data.get_group(time)[(data.get_group(time)['start_time']>= wts) & (data.get_group(time)['start_time']<= wte)]['start_time'].count()
#     print(countZ,countW)time = pd.Timestamp(time)times.append(time)countZs.append(countZ)countWs.append(countW)
workdf = pd.DataFrame()
workdf['time']=times
workdf['countZ']=countZs
workdf['countW']=countWs
workdf['time'] = pd.to_datetime(workdf['time'])
workday = pd.date_range(start='2016-08-01',end='2016-08-31 ',freq='B')
workdf[workdf['time'].isin(workday)][workdf['countZ']>workdf['countW']]

统计出8月份每周五的记录量

f = df[df['work_week']==4].groupby('new_start_time')
print(f.size())

data = df[df['new_start_time']==pd.to_datetime('2016-08-26')]
data['end_time'] = pd.to_datetime(data['end_time'])
data['start_time'] = pd.to_datetime(data['start_time'])
data['time_sep'] = (data['end_time']-data['start_time']).dt.seconds/60
data['new_time_sep'] = pd.cut(data['time_sep'],[0,30,120,360],labels=['one','two','three'])
data.set_index(['new_time_sep'])
one = data[data['new_time_sep']=='one']['time_sep'].mean()
two = data[data['new_time_sep']=='two']['time_sep'].mean()
three = data[data['new_time_sep']=='three']['time_sep'].mean()
print(one,two,three)

#公式计算
import math
lon1 = df['start_location_x']
lat1 = df['start_location_y']
lon2 = df['end_location_x']
lat2 = df['end_location_y']
R = 6371
dlon = lon2 - lon1 
dlat = lat2 - lat1 
a = (np.sin(dlat/2))**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon/2))**2 
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))
d = R * c #geopy
!pip install geopy
import geopy.distance
# print (geopy.distance.distance(coords_1, coords_2).km)
lon1 = df['start_location_x'].tolist()
lat1 = df['start_location_y'].tolist()
lon2 = df['end_location_x'].tolist()
lat2 = df['end_location_y'].tolist()
coords_1 = list(zip(lat1, lon1))
coords_2 = list(zip(lat2, lon2))
dist = []
for i,j in zip(coords_1,coords_2):dis = geopy.distance.distance(i, j).kmdist.append(dis)

#距离
df['dis'] = d#匀速=距离/时间
df['sudu'] = df['dis']/df['time_sep']#3sigmoid筛选一禅  
Dmean = df['sudu'].mean()
Dstd = df['sudu'].std()
#阈值
thre1 = Dmean-3*Dstd
thre2 = Dmean+3*Dstd
#异常值
outlies = df[(df['sudu']<thre1) | (df['sudu']>thre2)]

画图展示:

#未处理之前
plt.figure()
plt.scatter(range(df.shape[0]),df['sudu'].tolist())
plt.xlabel('用户')
plt.ylabel('速度值')
plt.title('未处理缺失值-速度图像')
plt.show()#处理之后
Dmean = df['sudu'].mean()
Dstd = df['sudu'].std()thre1 = Dmean-3*Dstd
thre2 = Dmean+3*Dstdoutlies = df.index[(df['sudu']<thre1) | (df['sudu']>thre2)]data = df.drop(outlies,axis=0)plt.figure()
plt.scatter(range(data.shape[0]),data['sudu'].tolist())
plt.xlabel('用户')
plt.ylabel('速度值')
plt.title('处理缺失值-速度图像')
plt.show()

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/466787.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux C高级编程——文件操作之库函数

Linux C高级编程——文件操作之库函数 宗旨&#xff1a;技术的学习是有限的&#xff0c;分享的精神是无限的 ——为什么要设计标准I/O库&#xff1f; 直接使用API进行文件访问时&#xff0c;需要考虑许多细节问题 例如&#xff1a;read、write时&#xff0c;缓冲区的大小该如…

【转】spring之任务调度

由于现在大部分的系统都是采用了spring&#xff0c;所以所有的例子都结合spring来构建&#xff0c;目前主要的任务调度分为三种&#xff1a; Java自带的java.util.Timer类&#xff0c;这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执…

测试内存对齐对运行速度的影响

我们知道内存对齐是为了方便CPU工作&#xff0c;但是对齐和不对齐差异有多大呢&#xff1f;我自己也没有实际测试过&#xff0c;今天就运行个代码测试看看。1、1字节对齐的时候#include "stdio.h"#pragma pack(1) struct test { char x1; short x2; float x3; …

连接池的问题

看到关于连接池的问题&#xff0c;觉得很有用&#xff0c;摘录到自己博客上 NET 连接池救生员 防止可淹没应用程序的池溢出 William Vaughn 大多数 ADO.NET 数据提供程序使用连接池&#xff0c;以提高围绕 Microsoft 断开连接的 .NET 结构构建的应用程序的性能。应用程序首先打…

Datawhale-零基础入门NLP-新闻文本分类Task01

参考&#xff1a; https://www.jianshu.com/p/56061b8f463a 统计自然语言处理 宗成庆&#xff08;第二版&#xff09; 文本自动分类简称文本分类(text categorization),是模式识别与自然语言处理密切结合的研究课题.传统的文本分类是基于文本内容的,研究如何将文本自动划分为…

fprintf/fscanf函数分析

fprintf/fscanf函数分析 宗旨&#xff1a;技术的学习是有限的&#xff0c;分享的精神是无限的。 fprintf/fscanf函数与printf/scanf区别&#xff1a;printf/scanf专门针对标准输入输出流&#xff0c;fprintf/fscanf函数可用于任意流&#xff0c;包括输入输出流。 1、fprintf …

华为海选开发者状元?还送14件豪礼?

华为云全年最大 最大 最大开发者庆典活动来啦&#xff01;这次庆典没别的&#xff0c;就是&#xff1a;好玩&#xff01;刺激&#xff01;让你拿奖拿到怀疑人生&#xff01;贺岁就要有贺岁的样子~赶紧来看看华为云为开发者们准备了怎样的新年惊喜好玩的在这里&#xff01;上学的…

国际:如何识别真正的程序员

如何识别优秀的程序员&#xff1f;并不是像听起来那么容易。在这儿工作经验的作用是很有限的&#xff0c;因为伟大的程序员不一定要‘正式’的工作经历来证明他们的伟大。 1&#xff0c;激情。 我曾经遇到许多“职业程序员”&#xff0c;他们从事IT是因为觉得这是一种职业&…

Datawhale-零基础入门NLP-新闻文本分类Task02

Task01里边对赛题进行了分析,接下来进行数据读取与数据分析&#xff0c;通过使用Pandas库完成数据读取和分析操作。 1 数据读取 由赛题数据格式可知&#xff0c;可通过read_csv读取train_set.csv数据&#xff1a; import pandas as pd import numpy as np import matplotlib…

一步步分析-C语言如何面向对象编程

这是道哥的第009篇原创一、前言在嵌入式开发中&#xff0c;C/C语言是使用最普及的&#xff0c;在C11版本之前&#xff0c;它们的语法是比较相似的&#xff0c;只不过C提供了面向对象的编程方式。虽然C语言是从C语言发展而来的&#xff0c;但是今天的C已经不是当年的C语言的扩展…

Linux C高级编程——目录操作

Linux C目录操作 宗旨&#xff1a;技术的学习是有限的&#xff0c;分享的精神是无限的。 Linux思想“一切皆文件”&#xff0c;目录也是文件&#xff0c;只是存储的内容有别于普通文件。目录文件中存储的该目录下所有的文件及子目录文件的信息&#xff0c;inode节点。 一、打开…

利用open***建立桥接***[zt]

利用open***建立桥接***http://blog.chinaunix.net/u/7667/showart_30753.html本文介绍利用open***建立桥接***的一种简单方法&#xff0c;使用的服务器为debian GNU/Linux sarge,使用apt-get dist-upgrade更新到最新&#xff0c;内核2.4.27-1-686&#xff0c;未重新编译内核&a…

c复习过程随笔四

使用scanf函数输入数据&#xff1a;一般形式&#xff08;格式控制&#xff0c;地址表列&#xff09; 格式控制中可以包含普通字符 格式控制和printf函数所遵循的格式相似 使用scanf应注意的问题&#xff1a; &#xff08;1&#xff09;格式控制后面应该是变量地址&#xff0c;而…

Datawhale-零基础入门NLP-新闻文本分类Task03

文本是不定长度的&#xff0c;文本表示成计算的能够运算的数字或向量的方法称为词嵌入&#xff08;Word Embedding&#xff09;。词嵌入是将不定长的文本转换成定长的空间中。为了解决将原始文本转成固定长度的特征向量问题&#xff0c;scikit-learn提供了以下方法&#xff1a;…

Linus 在圣诞节想提前放假做了这些解释,哈哈哈

最近在 lkml.org 上看到Linus发布的一个信息&#xff0c;挺有意思的&#xff0c;我看了内容&#xff0c;然后根据自己的理解展示给大家看看&#xff0c;如果有不对的地方欢迎指正。好的&#xff0c;5.10内核发布了我真希望在圣诞节来的最后一个星期没有那么多破事&#xff0c;现…

文件流、目录流、文件描述符总结

文件流、目录流、文件描述符总结 宗旨&#xff1a;技术的学习是有限的&#xff0c;分享的精神是无限的。 内核为使当前进程与进程打开的文件建立联系&#xff0c;在进程PCB&#xff08;一个结构体task_struct&#xff09;中使用一个成员来指向关于打开文件列表的结构体struct …

eleemnt-ui修改主题颜色

饿了吗的element-ui使用的是淡蓝色的主题&#xff0c;有时候我们可以自定义主题&#xff0c;官方的文档给我们提供了如何修改主题&#xff0c;介绍的很详细&#xff0c;自己试验过后&#xff0c;觉得很不错&#xff0c;一方面怕忘记&#xff0c;一方面写一写。 方法一是在线生成…

Datawhale-零基础入门NLP-新闻文本分类Task04

1 FastText 学习路径 FastText 是 facebook 近期开源的一个词向量计算以及文本分类工具,FastText的学习路径为&#xff1a; 具体原理就不作解析了,详细教程见&#xff1a;https://fasttext.cc/docs/en/support.html 2 FastText 安装 2.1 基于框架的安装 需要从github下载源…

多重 for 循环,如何提高效率?

2258 字 14 图 : 文章字数6 分钟 : 预计阅读网络 : 内容来源BabyCoder : 编辑整理前言我在《华为 C 语言编程规范》中看到了这个&#xff1a;当使用多重循环时&#xff0c;应该将最忙的循环放在最内层。如下图&#xff1a;由上述很简单的伪代码可以看到&#xff0c;推荐使用的方…

【转】Web服务软件工厂

patterns & practices开发中心 摘要 Web服务软件工厂(英文为Web Service Software Factory&#xff0c;也称作服务工厂)是一个集成的工具、模式、源代码和规范性指导的集合。它的设计是为了帮助你迅速、一致地构建符合普遍的体系结构和设计模式的Web服务。 如果你是一名负责…