首页 > 解决方案 > 如何使用rpy2在R识别为空的熊猫中创建空单元格?

问题描述

我正在尝试执行下面的操作,这些操作可以正常工作,除了 R 无法将空单元格识别为空的问题。当R抱怨有两个以上的因素时会出现此错误;R 认为标记为“nan”的单元格实际上不是空的。

# Set up the df
d = {'col1': [1, 2, 3, 4, 3, 3, 2, 2], 'col2': [1, 2, 3, 4, 3, 3, 2, 2]}
df = pd.DataFrame(data=d)
df['valence_median_split'] = ''

#Get median of valence
valence_median = df['col1'].median()
df['valence_median_split'] = np.where(df['col2'] < valence_median, 'Low_Valence', 'High_Valence')
df['temp_selection'] = np.nan
low = df.loc[df['valence_median_split'] == 'Low_Valence', 'valence_median_split'].sample(n=2).index
high = df.loc[df['valence_median_split'] == 'High_Valence', 'valence_median_split'].sample(n=2).index
df['temp_selection'] = np.select([df.index.isin(low), df.index.isin(high)], ['Low', 'High'], default= np.nan)

# Push it to R and run a t-test
%Rpush df
%R colnames(df)
%R All_Valence_Mean_Res <- t.test(col2 ~ temp_selection, data = df, var.equal = TRUE)

错误:

Error in t.test.formula(col2 ~ temp_selection, data = df, var.equal = TRUE) : 
  grouping factor must have exactly 2 levels

在 python 中验证 df 确实有超过 2 个唯一值:

df['temp_selection'].unique()
array(['Low', 'nan', 'High'], dtype=object)

我尝试将 df['valence_median_split'] 设置为 '' 以及 np.nan,两者似乎都在 R 中产生了这个问题。

标签: pythonrpandasnumpydataframe

解决方案


这个够小了,可以看整个df:

In [821]: df                                                                    
Out[821]: 
   col1  col2 valence_median_split temp_selection
0     1     1          Low_Valence            nan
1     2     2          Low_Valence            nan
2     3     3         High_Valence            nan
3     4     4         High_Valence            nan
4     3     3         High_Valence           High
5     3     3         High_Valence           High
6     2     2          Low_Valence            Low
7     2     2          Low_Valence            Low

在什么意义上一个nan值被认为是“空的”?


推荐阅读