python - 错误“只能比较相同标记的系列对象”和 sort_index

标签 python pandas indexing boolean

我有两个数据帧 df1 df2 具有相同的行数和列数以及变量,我正在尝试比较 boolean 变量 choice 在两个数据框中。然后使用if/else 来操作数据。但是当我尝试比较 boolean 变量时,似乎出了点问题。

这是我的数据框示例和代码:

#df1
v_100     choice #boolean
7          True
0          True
7          False
2          True

#df2
v_100     choice #boolean
1          False
2          True
74         True
6          True

def lastTwoTrials_outcome():
     df1 = df.iloc[5::6, :] #df1 and df2 are extracted from the same dataframe first
     df2 = df.iloc[4::6, :]

     if df1['choice'] != df2['choice']:  # if "choice" is different in the two dataframes
         df1['v_100'] = (df1['choice'] + df2['choice']) * 0.5

这是错误:

if df1['choice'] != df2['choice']:
File "path", line 818, in wrapper
raise ValueError(msg)
ValueError: Can only compare identically-labeled Series objects

我发现了同样的错误here , 一个答案建议首先 sort_index ,但我真的不明白为什么?谁能更详细地解释一下(如果这是正确的解决方案)?

谢谢!

最佳答案

我想你需要reset_index对于相同的索引值,然后比较 - 为了创建新列,最好使用 masknumpy.where :

另外 + 使用 | 因为使用 boolean 值。

df1 = df1.reset_index(drop=True)
df2 = df2.reset_index(drop=True)
df1['v_100'] = df1['choice'].mask(df1['choice'] != df2['choice'],
                                  (df1['choice'] + df2['choice']) * 0.5)


df1['v_100'] = np.where(df1['choice'] != df2['choice'],
                       (df1['choice'] | df2['choice']) * 0.5,
                        df1['choice'])

示例:

print (df1)
   v_100  choice
5      7    True
6      0    True
7      7   False
8      2    True

print (df2)
   v_100  choice
4      1   False
5      2    True
6     74    True
7      6    True

df1 = df1.reset_index(drop=True)
df2 = df2.reset_index(drop=True)
print (df1)
   v_100  choice
0      7    True
1      0    True
2      7   False
3      2    True

print (df2)
   v_100  choice
0      1   False
1      2    True
2     74    True
3      6    True

df1['v_100'] = df1['choice'].mask(df1['choice'] != df2['choice'],
                                  (df1['choice'] | df2['choice']) * 0.5)

print (df1)
   v_100  choice
0    0.5    True
1    1.0    True
2    0.5   False
3    1.0    True

关于python - 错误“只能比较相同标记的系列对象”和 sort_index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44773017/

相关文章:

python - 如何在 pandas 中一次对 `n` 行进行求和?

python - python 列表中每个月的工作日

pandas - cython 函数在 groupby 应用后返回单个单元格中的所有值

java - AppEngine Java 重新索引任务/映射器/作业

mysql - 如何为长文本创建索引(mysql、innodb)?

python - Pygame 事件处理程序相互干扰?

python - 正则表达式排除表达式中的字符串和属性

python - pip 失败,出现 AttributeError : 'module' object has no attribute 'wraps'

python - numpy 数组中元素的顺序

python - 为什么 Django 测试无法识别我的 App 测试?