• Data manipulation primitives in R and Python


    Data manipulation primitives in R and Python

    Both R and Python are incredibly good tools to manipulate your data and their integration is becoming increasingly important1. The latest tool for data manipulation in R is Dplyr2 whilst Python relies onPandas3.

    In this blog post I'll show you the fundamental primitives to manipulate your dataframes using both libraries highlighting their major advantages and disadvantages.

     

    Theory first

    Data Frames are basically tables. Codd, E.F. in 1970 defined Relational algebra4 as the basic the theory to work on relational tables. It defines the following operations:

    • Projection (π)
    • Selection (σ)
    • Rename (ρ)
    • Set operators (union, difference, cartesian product)
    • Natural join (⋈)

    SQL dialects also added the following

    • Aggregations
    • Group by operations

    Why we care? People redefined these basic operations over and over in the last 40 years starting with SQL until today latest query languages. This framework will give us a general language independent perspective on the data manipulation.

    Hands on

    I will use the nycflights13 dataset used to introduce dplyr5 to present the functions. If you are interested you can download this entire blog post as an IPython notebook. Let's initialise our environment first:

     

     

    Data summary

    In both libraries it is possible to quickly print a quick summary of your dataframe. Pandas has an object oriented approach and you can invokehead()tail() and describe() directly on your dataframe object. R has a procedural approach and its functions take a dataframe as the first input.

    PythonR
    df.head() head(df)
    df.tail() tail(df)
    df.describe() summary(df)

     

     

    Selection

    In pandas in order to select multiple rows you need to use the []operator with the element-wise operators like & and |. If you don't use the element-wise operators you will get the following error: ValueError: The truth value of a Series is ambiguous. Another solution is to install the numexpr6 package and use the query() function.

    dplyr instead provides the filter() function. Combined with the pipe operator %>% the code is incredibly readable in my opinion. Notice how repeating the dataframe variable in the boolean expression is not needed in this case.

    PythonR
    df[bool expr with element-wise operators] df %>% filter(bool expr)
    df.query('bool expr')  

     

     

    Projection

    You can use the projection operation to extract one (or more) columns from a dataframe. In Python you pass an array with the columns you are interested in to the DataFrame object. In dplyr the projection function is called select, inspired by SQL.

    PythonR
    df[['col_1', 'col_2']] df %>% select(col_1, col_2)

     

     

    Rename

    The rename operation is used to simply rename a column of your dataframe keeping the content intact. In pandas you use the rename7function and you provide a dictionary. In R you use a comma separated list of assignments.

    PythonR
    df.rename(columns={'col_name': 'col_new_name'}) df %>% rename(col_new_name = col_name)

     

     

    Union

    The relational algebra uses set union, set difference, and Cartesian product from set theory, with the extra constraint that tables must be "compatible", i.e. they must have the same columns.

    You can use the union in Pandas using the concat()8 operation. You need to take some extra care for indexes though and for that I'll forward you to the docs9.

    In R you rely on the bind_rows10 operator.

    PythonR
    concat([df_1, df_2]); rbind_list(df_1, df_2)

     

     

    Difference

    To the best of my knowledge there is no set difference operator in Python. In order to achieve the result we must rely on the select operator.

    In dplyr there is a native operator setdiff that does exactly what we expect.

    PythonR
    set_a[~set_a.column.isin(set_b.column)] set_a %>% setdiff(set_b)

     

     

    Cartesian product

    You can use the cartesian product to combine two tables with a disjoint set of columns. In practice this is not a very common operation and as a result both libraries lack a pure cartesian product (in favour of the way more common join operator).

    A simple trick to overcome this limitation is to create a temporary column first, perform the join and finally remove the temporary column. This can be done both in Python and R using the merge() andfull_join methods.

    PythonR
    merge(...) with tmp column full_join(...) with tmp column

     

     

    Natural Join

    If you are used to SQL you are definitely aware of what a join operation is. Given two dataframe R and S the result of the natural join is the set of all combinations of tuples in R and S that are equal on their common attribute names.

    In Python you can rely on the very powerful merge11 command.
    In R Dplyr you can use the full_join12 command.

    PythonR
    merge(..., on="key", how="outer") full_join(..., by="key")

     

     

    Aggregations

    An aggregate function is a function that takes the values of a certain column to form a single value of more significant meaning. Typical aggregate functions available in the most common SQL dialects include Average(), Count(), Maximum(), Median(), Minimum(), Mode(), Sum().

    Both R and Python dataframes provides methods to extract this information. In this case I would say that Python handle missing values default better, whilst on R we have to provide na.rm = TRUE.

    PythonR
    df.<column>.mean() summarise(df, test=mean(<column>, na.rm = TRUE))
    df.<column>.median() summarise(df, test=median(<column>, na.rm = TRUE))
    df.<column>.std() summarise(df, test=sd(<column>, na.rm = TRUE))
    df.<column>.var() summarise(df, test=var(<column>, na.rm = TRUE))
    df.<column>.min() summarise(df, test=min(<column>, na.rm = TRUE))
    df.<column>.max() summarise(df, test=max(<column>, na.rm = TRUE))

     

     

    Group by

    Aggregations become useful especially when used in conjunction with the group by operator. This way we are able to compute statistics for a number of group subsets with just one command.

    Both Python and R provides the function to run a group by.

    PythonR
    df.groupby('<column>') df %>% group_by(<column>)

     

     

    Conclusion

    I think the Pandas and Dplyr paradigms are very different between each other.

    Pandas is more focused on object orientation and good defaults. Indexes are a first class entity and as a result some operations that you expect to be simple are instead quite difficult to grasp.

    Conversely Dplyr is procedural. I love the pipe operator and manipulating my data feels incredibly smooth. The only sad note is that sometimes functions defaults are not that great. I haven't tested the speed in this blog post but I assume that since indexes are hidden in Dplyr the speed is probably much lower in general.

    In conclusion I feel like Dplyr and R are the perfect tool for some early exploration of the data. But if you are serious about the code you are producing you should probably switch to Python to productionise your data analysis.

    Let me know your approach in the comments!

    References

      1. IEEE 2015 top programming languages
      2. Dplyr homepage
      3. Pandas homepage
      4. Relational Algebra
      5. NYC Flights 2013 dataset
      6. Numexpr python package
      7. pandas.DataFrame.rename
      8. Merging data frames in Panda
      9. Concatenating objects in Pandas
      10. Dplyr bind function
      11. Pandas merge function
      12. Dplyr documentation
  • 相关阅读:
    Tomcat 加载 jsp 异常:ServletException: java.lang.LinkageError
    SpringMvc CharacterEncodingFilter 解析 encoding 参数并初始化参数
    查看 chrome 浏览器中的 Headers
    SpringMvc @PathVariable 工作原理
    SpringMvc HandlerMethodResolver 的 handlerMethods & ServletHandlerMethodResolver 的 mappings 在哪里初始化的 ?
    SpringMvc HandlerMappings 何时初始化?
    scanperiod 不生效
    SLF4J bindings
    spring-boot 根据环境启动
    TmeUnit
  • 原文地址:https://www.cnblogs.com/yymn/p/4705610.html
Copyright © 2020-2023  润新知