python - 如何使用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 中产生了这个问题。
解决方案
这个够小了,可以看整个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
值被认为是“空的”?
推荐阅读
- python - 使用列表中的数据在 seaborn 中创建小提琴图
- mysql - 将 Sqlserver 转换为 Mysql 服务器
- sql - SQL SELECT 用于一对多特征关系以选择具有某些特征的键
- javascript - 反应路由器“内容安全策略指令”错误
- command-line - 静默安装失败,Resultcode = -8 [现在 ResultCode 0 但未安装]
- javascript - 使用 setState 更改复选框的状态
- android - 手动输入密码后启用 Samsung Pass
- web - 关于发展基础的书籍(主要是网络)
- c# - 如何在不在模型中的情况下从视图上传或下载文件
- java - Drools:无法反序列化知识库