[英]unsigned integer error while trying to convert pandas dataframe to R's dataframe using rpy2
我有以下數據:
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)))
這可以修復還是我需要一起刪除這些列,例如,如果出現此錯誤,只需跳過該列?
有人可以幫我解決這個問題嗎?
您可以使用astype()
從pandas
以所有元素的轉換在pandas
數據幀所需dtype
。 在這種情況下,我們只想將您的虛擬變量轉換為 R 理解的內容。 假設您的數據框仍命名為“data”,請嘗試以下代碼:
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)
馬庫斯的回答對我幫助很大。
在我的例子中,我認為這個問題的Pandas.DataFrame
是numpy.uint8
在被pd.get_dummies()
轉換為虛擬變量后被轉換為pd.get_dummies()
。
因此,在應用pandas2ri.py2ri(data)
之前,我只是通過astype()
將其轉換為'int64'
,最后我修復了該錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.