Sample datasets in Pandas

前端 未结 4 1251
醉酒成梦
醉酒成梦 2021-01-29 23:43

When using R it\'s handy to load \"practice\" datasets using

data(iris)

or

data(mtcars)

Is there something s

4条回答
  •  感情败类
    2021-01-29 23:43

    The rpy2 module is made for this:

    from rpy2.robjects import r, pandas2ri
    pandas2ri.activate()
    
    r['iris'].head()
    

    yields

       Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
    1           5.1          3.5           1.4          0.2  setosa
    2           4.9          3.0           1.4          0.2  setosa
    3           4.7          3.2           1.3          0.2  setosa
    4           4.6          3.1           1.5          0.2  setosa
    5           5.0          3.6           1.4          0.2  setosa
    

    Up to pandas 0.19 you could use pandas' own rpy interface:

    import pandas.rpy.common as rcom
    iris = rcom.load_data('iris')
    print(iris.head())
    

    yields

       Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
    1           5.1          3.5           1.4          0.2  setosa
    2           4.9          3.0           1.4          0.2  setosa
    3           4.7          3.2           1.3          0.2  setosa
    4           4.6          3.1           1.5          0.2  setosa
    5           5.0          3.6           1.4          0.2  setosa
    

    rpy2 also provides a way to convert R objects into Python objects:

    import pandas as pd
    import rpy2.robjects as ro
    import rpy2.robjects.conversion as conversion
    from rpy2.robjects import pandas2ri
    pandas2ri.activate()
    
    R = ro.r
    
    df = conversion.ri2py(R['mtcars'])
    print(df.head())
    

    yields

        mpg  cyl  disp   hp  drat     wt   qsec  vs  am  gear  carb
    0  21.0    6   160  110  3.90  2.620  16.46   0   1     4     4
    1  21.0    6   160  110  3.90  2.875  17.02   0   1     4     4
    2  22.8    4   108   93  3.85  2.320  18.61   1   1     4     1
    3  21.4    6   258  110  3.08  3.215  19.44   1   0     3     1
    4  18.7    8   360  175  3.15  3.440  17.02   0   0     3     2
    

提交回复
热议问题