[Python/R语言] 用R和python解决数据分析120题 21-50

转载请注明:陈熹 chenx6542@foxmail.com (简书号:半为花间酒)
若公众号内转载请联系公众号:早起Python
题源:
公众号 早起python 《Pandas进阶修炼120题》

数据:
https://pan.baidu.com/s/1YTYB4zuyPNYDoNoj2pCh6Q
提取码:p5yn

数据分析120题系列:

为什么出这个专题:

R语言和pandas都是数据处理的重要工具
而二者的高下争论时有存在
我相信对于数据而言没有绝对的孰优孰劣
需要做的应该是在必要时权衡最合适的办法

感谢 公众号早起python 提供数据分析120题
这些题目是一个契机
帮助我比较了两种语言处理不同问题的共性
当然也发现了各自的灵活和缺陷

它们覆盖多数数据分析初期可能遇到的问题
无论是对R语言还是对python技能的提升
相信都有很大帮助

(陈熹 2020年4月)

  • python解法
import pandas as pd
import numpy as np

df = pd.read_excel(r'C:\Users\chenx\Documents\Data Analysis\pandas120.xlsx')
  • R解法
    R语言原生函数处理excel不友好,直接读取日期时间数据会变成实数
    openxlsx::read.xlsx中的detectDates参数只能识别纯日期
    as.Data转换该列后时间数据丢失,只有日期
    可以先把excel文件转存为csv后用readr包读取
    另外再推荐非常智能的rio包,对格式的识别和属性的解析非常强
# 该方法不理想
library(openxlsx)
df <- read.xlsx('pandas120.xlsx',detectDates = T)
df$createTime <- as.Date(df$createTime,origin="1900-01-01")

# 转存csv后再读
library(readr)
df <- read_csv('pandas120.csv')
# 本题用这种方法,但需要注意createTime属性被解析成chr

# 强烈推荐rio包,一步到位,功能强大,解析成功率高
df <- rio::import('pandas120.xlsx')
pandas / R

  • python解法
df.head()
  • R解法
# 默认是6行,可指定行数
head(df,5)
pandas / R

  • python解法
# 方法一:apply + 自定义函数
def func(df):
    lst = df['salary'].split('-')
    smin = int(lst[0].strip('k'))
    smax = int(lst[1].strip('k'))
    df['salary'] = int((smin + smax) / 2 * 1000)
    return df

df = df.apply(func,axis=1) 

# 方法二:iterrows + 正则
import re

for index,row in df.iterrows():
    nums = re.findall('\d+',row[2])
    df.iloc[index,2] = int(eval(f'({nums[0]} + {nums[1]}) / 2 * 1000'))
  • R解法
    同理也可以自定义函数 + apply,这里用其他方法
library(stringr)
df$salary <- df$salary %>% 
  str_replace_all('k','') %>% 
  str_split('-',simplify = T) %>% 
  apply(2,as.numeric) %>% 
  rowMeans() * 1000
pandas / R

  • python解法
df.groupby('education').mean()
  • R解法
df %>% 
  group_by(education) %>% 
  summarise(mean = mean(salary))
pandas / R

  • python解法
for index,row in df.iterrows():
   df.iloc[index,0] = df.iloc[index,0].to_pydatetime().strftime("%m-%d")
  • R解法
    转化后该列属性是 字符串,R中对时间格式要求严格
df$createTime <- as.Date(df$createTime) %>% 
  str_replace('2020-','')
pandas / R

  • python解法
df.info()
  • R解法
str(df)

# 内存查看需要用到其他的库
library(pryr)
object_size(df)
# 6.66 kB
pandas / R

  • python解法
df.describe()
  • R解法
summary(df)
pandas / R

  • python解法
bins = [0,5000, 20000, 50000]
group_names = ['低', '中', '高']
df['categories'] = pd.cut(df['salary'], bins, labels=group_names)
  • R解法
    用ifelse也可以
    底层原理有差别但实现结果一样
df <- df %>% 
  mutate(categories = case_when(
    salary >= 0 & salary < 5000 ~ '低',
    salary >= 5000 & salary < 20000 ~ '低',
    TRUE ~ '高'
  ))
pandas / R

  • python解法
df.sort_values('salary', ascending=False)
  • R解法
df %>% 
  arrange(desc(salary))
pandas / R

  • python解法
df.iloc[32]
  • R解法
df[33,]
pandas / R

  • python解法
np.median(df['salary'])
# 17500.0
  • R解法
median(df$salary)
# [1] 17500


(R的可视化采用ggplot2包

  • python解法
# Jupyter运行matplotlib成像需要运行魔术命令
%matplotlib inline

plt.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码
plt.rcParams['axes.unicode_minus'] = False # 解决符号问题

import matplotlib.pyplot as plt
plt.hist(df.salary)

# 也可以用原生绘图
df.salary.plot(kind='hist')
  • R解法
library(ggplot2)
library(patchwork)

df %>% 
  ggplot(aes(salary)) +
  geom_histogram() + 
  df %>% 
  ggplot(aes(salary)) +
  geom_histogram(bins = 10) # 这个跟python的bins一致
pandas / R

  • python解法
df.salary.plot(kind='kde',xlim = (0,70000))
  • R解法
df %>% 
  ggplot(aes(salary)) +
  geom_density() +
  xlim(c(0,70000))
pandas / R

  • python解法
del df['categories']
# 等价于
df.drop(columns=['categories'], inplace=True)
  • R解法
df <- df[,-4]
# 提高可读性可采用如下代码
df <- df %>% 
  select(-c('categories'))
pandas / R

  • python解法
df['test'] = df['education'] + df['createTime']
  • R解法
df <- df %>% 
  mutate(test = paste0(df$education,df$createTime))
pandas / R

  • python解法
df["test1"] = df["salary"].map(str) + df['education']
  • R解法
df <- df %>% 
  mutate(test1 = 
           paste0(df$salary,df$education))
pandas / R

  • python解法
df[['salary']].apply(lambda x: x.max() - x.min())
# salary    41500
# dtype: int64
  • R解法
df %>% 
  summarise(delta = max(salary) - min(salary)) %>% 
  unlist()
# delta 
# 41500 

  • python解法
pd.concat([df[1:2], df[-1:]])
  • R解法
rbind(df[1,],df[dim(df)[1],])
pandas / R

  • python解法
df.append(df.iloc[7])
  • R解法
rbind(df,df[8,])
pandas / R

  • python解法
df.dtypes
# createTime    object
# education     object
# salary         int64
# test          object
# test1         object
# dtype: object
  • R解法
str(df)
# tibble [135 x 5] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
#  $ createTime: chr [1:135] "03-16" "03-16" "03-16" "03-16" ...
#  $ education : chr [1:135] "本科" "本科" "不限" "本科" ...
#  $ salary    : num [1:135] 27500 30000 27500 16500 15000 14000 23000 12500 7000 16000 ...
#  $ test      : chr [1:135] "本科03-16" "本科03-16" "不限03-16" "本科03-16" ...
#  $ test1     : chr [1:135] "27500本科" "30000本科" "27500不限" "16500本科" ...

  • python解法
df.set_index("createTime")
  • R解法
    createTime中含大量重复数据
    R中行索引要求必须是无重复,因此无法设置
    方法如下:
df %>% 
  tibble::column_to_rownames('createTime')
pandas / R

  • python解法
df1 = pd.DataFrame(pd.Series(np.random.randint(1, 10, 135)))
  • R解法
df1 <- sapply(135,function(n) {
  replicate(n,sample(1:10,1))
})
# 列名暂时不一样,下一题重命名
pandas / R

  • python解法
df= pd.concat([df,df1],axis=1)
  • R解法
df <- cbind(df,df1) %>% 
  rename(`0` = df1)
# 非常规命名需要用``包裹变量名
pandas / R

  • python解法
df["new"] = df["salary"] - df[0]
  • R解法
df <- df %>% 
  mutate(new = salary - `0`)
pandas / R

  • python解法
df.isnull().values.any()
# False
  • R解法
# 这个包的结果呈现非常有趣
library(mice)
md.pattern(df)
R

  • python解法
df['salary'].astype(np.float64)
  • R解法
as.double(df2$salary)
pandas / R

  • python解法
len(df[df['salary'] > 10000])
# 119
  • R解法
df %>% 
  filter(salary > 10000) %>% 
  dim(.) %>% 
  .[1]
# [1] 119

  • python解法
df.education.value_counts()
  • R解法
table(df$education)

  • python解法
df['education'].nunique()
# 4
  • R解法
length(unique(df$education))
# [1] 4

  • python解法
rowsums = df[['salary','new']].apply(np.sum, axis=1)
res = df.iloc[np.where(rowsums > 60000)[0][-3:], :]
  • R解法
df[df$salary + df$new > 60000,] %>% 
  .[nrow(.)-3+1:nrow(.),] %>% 
  na.omit(.)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 230,527评论 6 544
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,687评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,640评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,957评论 1 318
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,682评论 6 413
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 56,011评论 1 329
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 44,009评论 3 449
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 43,183评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,714评论 1 336
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,435评论 3 359
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,665评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,148评论 5 365
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,838评论 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,251评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,588评论 1 295
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,379评论 3 400
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,627评论 2 380

推荐阅读更多精彩内容