我有两个dataframes df1
df2
具有相同数量的行,列和变量,我正在尝试比较两个dataframes中的boolean变量 choice
。然后使用if/else
操纵数据。但是,当我尝试比较布尔值时,似乎有问题。
这是我的数据框样本和代码:
#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
我在这里发现了同样的错误,并且首先向sort_index
提出了答案,但是我真的不明白为什么?谁能详细解释(如果这是正确的解决方案(?
谢谢!
我认为您需要 reset_index
才能获得相同的索引值,然后comapare-为创建新列更好地使用 mask
或 numpy.where
:
也是+
使用|
,因为与布尔一起工作。
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
发生了错误,因为您比较了两个带有不同索引的pandas对象。一个简单的解决方案是仅比较系列中的值。尝试:
if df1['choice'].values != df2['choice'].values