中国统计网Python与R竟可以无缝衔接!这个方法太神奇了!( 二 )


  • 在R中 , 向量是同一类型的有序项的可变集合 。 索引R中的向量从1开始 , 并且是包含的
  • Python# R ls = [1,'a',3,False] vc <- c(1,2,3,4)# Python indexing starts at0, R indexing starts at1 b = ls[0] b = vc[1] print(b)#returns 1 print(b) #returns 1c = ls[0:1] c = vc[1:2] print(c)#returns 1 print(c) #returns 1,循环
    数据操作
    python和R都提供了简单而精简的数据操作包 , 使它们成为数据科学家必不可少的工具 。
    这两种语言都配备了能够加载、清理和处理数据的包 。
    python使用pandas、R使用tidyverse , 并且他们的函数基本相同 。
    两种语言都允许多个操作通过管道(pipe)连接在一起 。 在python中使用“.” 在R中使用“%>%”组合不同的操作 。
    读取、写入和查看数据
    # Python # R importpandasaspd library(tidyverse) # load and view data df = pd.read_csv('path.csv') df <- read_csv('path.csv') df.head head(df) df.sample(100) sample(df,100) df.describe summary(df) # write to csv df.to_csv('exp_path.csv') write_csv(df,'exp_path.csv')重命名和添加列
    # Python # R df = df.rename({'a':'b'}, axis=1) df %>%rename(a = b) df.newcol = [1,2,3] df$newcol <- c(1,2,3) df['newcol'] = [1,2,3] df %>% mutate(newcol = c(1,2,3))选择和筛选列
    # Python # R df['col1','col2'] df %<%select(col1,col2) df.drop('col1') df %<%select(-col1)筛选行
    # Python # R df.drop_duplicates df%<% distinct df[df.col >3] df%<% filter(col >3)排序
    # Python # R df.sort_values(by='column') arrange(df, column)聚合
    #Python df.groupby('col1') ['agg_col').agg(['mean']).reset_index #R df %>% group_by(col1) %>% summarize(mean = mean(agg_col, na.rm=TRUE)) %>% ungroup #if resetting index使用筛选器聚合
    df.groupby('col1').filter(lambdax: x.col2.mean >10) # R df %>% group_by(col1) %>% filter(mean(col2) >10)合并dataframe
    # Python pd.merge(df1, df2, left_on="df1_col", right_on="df2_col") # R merge(df1, df2, by.df1="df1_col", by.df2="df2_col") 上面的例子是在Python和R之间创建心理相似性的起点 。 虽然大多数数据科学家倾向于使用一种语言或另一种语言 , 但是在这两种语言中都能很好地使用最适合您需要的工具 。
    我们的最终的目的并不是为了熟练的掌握另一门语言并用它开发 , 而是能够看懂另一门语言所写的代码 , 并把它的思想应用到我们自己的项目中去 。
    End.
    点分享点点赞点在看


    推荐阅读