【问题标题】:unsigned integer error while trying to convert pandas dataframe to R's dataframe using rpy2尝试使用 rpy2 将 pandas 数据帧转换为 R 的数据帧时出现无符号整数错误
【发布时间】:2018-09-22 15:45:53
【问题描述】:

我有以下数据:

grp_m1      grp_m2      grp_m3      grp_m4
$50-$75     $50-$75     $50-$75     $50-$75
$50-$75     $50-$75     $50-$75     $50-$75
$150-$175       $150-$175       $150-$175       $150-$175
$100-$125       $100-$125       $100-$125       $100-$125
$150-$175       $125-$150       $125-$150       $125-$150

这些然后被转换为假人。这些假人的 dtype 在 pandas 数据帧中是 unsigned int ,当我尝试使用以下代码将其转换为 R 数据帧时:

from rpy2.robjects import pandas2ri
pandas2ri.activate()
pandas2ri.py2ri(data)

我收到以下错误:

Error while trying to convert the column "grp_m4_$175-$200". Fall back to string conversion. The error is: Cannot convert numpy array of unsigned values -- R does not have unsigned integers.
  (name, str(e)))
C:\Users\hduser\AppData\Local\Continuum\anaconda3.1\lib\site-packages\rpy2-2.9.1-py3.6-win-amd64.egg\rpy2\robjects\pandas2ri.py:61: UserWarning: Error while trying to convert the column "grp_m4_$200-$225". Fall back to string conversion. The error is: Cannot convert numpy array of unsigned values -- R does not have unsigned integers.
  (name, str(e)))

这可以修复还是我需要一起删除这些列,例如如果出现此错误,请跳过该列?

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 我不会说 python,但如果解决方案是将这些值转换为有符号整数,我不会感到惊讶。

标签: python r pandas rpy2


【解决方案1】:

马库斯的回答对我帮助很大。

在我的例子中,我认为这个问题的主要原因是 Pandas.DataFrame 的项目在被转换为虚拟变量后被转换为 numpy.uint8 pd.get_dummies()

所以,我只是在应用pandas2ri.py2ri(data) 之前将其转换为'int64' by astype(),最后我修复了这个错误。

【讨论】:

    【解决方案2】:

    您可以使用pandas 中的astype()pandas 数据帧中的所有元素转换为所需的dtype。在这种情况下,我们只想将您的虚拟变量转换为 R 可以理解的东西。假设您的数据框仍命名为“数据”,请尝试以下代码:

    import pandas as pd
    
    # change unsigned integers to integers
    n_data = data.astype('int64') # you could also try float64, if you want
    
    # Check data type
    type(n_data.iat[0,0])
    
    # Output
    # <class 'numpy.int64'>
    
    from rpy2.robjects import pandas2ri
    pandas2ri.activate()
    
    pandas2ri.py2ri(data)
    

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 2022-08-14
      • 2016-09-27
      • 2022-08-16
      • 2021-09-15
      • 2020-07-24
      • 2015-09-08
      • 2021-05-29
      • 2017-02-04
      相关资源
      最近更新 更多