R语言

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

2020-04-14  本文已影响0人  半为花间酒

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

数据分析120题系列:

为什么出这个专题:

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

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

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

(陈熹 2020年4月)

import numpy as np
import pandas as pd

df = pd.DataFrame(data)

# 假如是直接创建
df = pd.DataFrame({
    "grammer": ["Python","C","Java","GO",np.nan,"SQL","PHP","Python"],
    "score": [1,2,np.nan,4,5,6,7,10]})
# R中没有字典概念,故直接创建dataframe/tibble
#> 第一种
df <- data.frame(
  "grammer" = c("Python","C","Java","GO",NA,"SQL","PHP","Python"),
  "score" = c(1,2,NA,4,5,6,7,10)
)

#> 第二种
library(tibble)
df <- tibble(
  "grammer" = c("Python","C","Java","GO",NA,"SQL","PHP","Python"), 
  "score" = c(1,2,NA,4,5,6,7,10)
)

# 也可以用tribble横向建tibble
pandas / R
#> 1
df[df['grammer'] == 'Python']

#> 2
results = df['grammer'].str.contains("Python")
results.fillna(value=False,inplace = True)
df[results]
df[which(df$grammer == 'Python'),]
pandas / R
df.columns
# Index(['grammer', 'score'], dtype='object')
names(df)
# [1] "grammer" "score"  

df.rename(columns={'score':'popularity'}, inplace = True)
df <- df %>% 
  rename(popularity = score)

df['grammer'].value_counts()
# 神方法table
table(df$grammer)
pandas / R
# pandas里有一个插值方法,就是计算缺失值上下两数的均值
df['popularity'] = df['popularity'].fillna(df['popularity'].interpolate())
library(Hmisc)
index <- which(is.na(df$popularity))
df$popularity <- impute(df$popularity,
                       (unlist(df[index-1, 2] + 
                               df[index+1, 2]))/2)
pandas / R
df[df['popularity'] > 3]
df %>% 
  filter(popularity > 3)
# 等价于
df[df$popularity > 3,] # 这种方法跟pandas很相似
pandas / R
df.drop_duplicates(['grammer'])
df[!duplicated(df$grammer),]
pandas / R
df['popularity'].mean()
# 4.75
#> 第一种
mean(df$popularity)
# [1] 4.75

#> 第二种
df %>% 
  summarise(mean = mean(popularity))
## A tibble: 1 x 1
#     mean
#    <dbl>
#  1  4.75

df['grammer'].to_list()
# ['Python', 'C', 'Java', 'GO', nan, 'SQL', 'PHP', 'Python']
unlist(df$grammer)
# [1] "Python" "C"      "Java"   "GO"     NA       "SQL"    "PHP"    "Python"

python还有其他处理EXCEL的包比如 openpyxl、xlrd、xlwt、xluntils等
本例用pandas的写入方法解决

df.to_excel('filename.xlsx')

R对EXCEL文件不太友好
第一种方法:利用readr包转为csv再用EXCEL打开
文件本质依然是csv

library(readr)
write_excel_csv(df,'filename.csv')

第二种方法:利用openxlsx包

openxlsx::write.xlsx(df,'filename.xlsx')

也可以用xlsx包,但需要先配置JAVA环境
确保JAVA配置到环境变量中并命名为JAVA_HOME

Sys.getenv("JAVA_HOME")
install.packages('rJava')
install.packages("xlsxjars")
library(rJava)
library(xlsxjars)
xlsx::write.xlsx(df,'filename.xlsx')

df.shape
# (8, 2)
dim(df)
# [1] 8 2

df[(df['popularity'] > 3) & (df['popularity'] < 7)]
library(dplyr)
df %>% 
  filter(popularity > 3 & popularity <7)
# 等价于
df[(df$popularity > 3) & (df$popularity <7),]
pandas / R
temp = df['popularity']
df.drop(labels=['popularity'], axis=1,inplace = True)
df.insert(0, 'popularity', temp)
df <- df %>% 
    select(popularity,everything())
pandas / R
df[df['popularity'] == df['popularity'].max()]
df %>% 
  filter(popularity == max(popularity)) 
# 同理也有类似pandas的方法
df[df$popularity == max(df$popularity),]
pandas / R
df.tail()
# R中head和tail默认是6行,可以指定数字
tail(df,5)
pandas / R
df = df.drop(labels=df.shape[0]-1)
df[-dim(df)[1],]
# 等价于
df %>% 
  filter(rownames(df) != max(rownames(df))) 
pandas / R
row = {'grammer':'Perl','popularity':6.6}
df = df.append(row,ignore_index=True)
row <- c(6.6,'Perl') # 需要和列的位置对应
# 或者建数据框
row <- data.frame(
  "grammer" = c("Perl"),
  "popularity" = c(6.6)
)

df <- rbind(df,row)
pandas / R
df.sort_values("popularity",inplace=True)
df <- df %>% 
  arrange(popularity)
pandas / R

从本题开始将grammer列中的缺失值替换为R

df['grammer'] = df['grammer'].fillna('R')

df['len_str'] = df['grammer'].map(lambda x: len(x))
library(Hmisc)
library(stringr)
df$grammer <- impute(df$grammer,'R')
str_length(df$grammer)

df$len_str <- str_length(df$grammer)
pandas / R
上一篇下一篇

猜你喜欢

热点阅读