Python 使用条件和索引更改数据帧中的值
我不明白为什么以下代码不起作用:Python 使用条件和索引更改数据帧中的值,python,pandas,dataframe,anaconda,Python,Pandas,Dataframe,Anaconda,我不明白为什么以下代码不起作用: df_sensor.loc[(df_sensor.user_id == labels_user_id) & (df_sensor.exp_id == labels_exp_id),'activity_id'].iloc[start:end] = labels['activity_id'][I] 这条线 df_sensor.loc[(df_sensor.user_id == labels_user_id) & (df_sensor.exp_id
df_sensor.loc[(df_sensor.user_id == labels_user_id) & (df_sensor.exp_id == labels_exp_id),'activity_id'].iloc[start:end] = labels['activity_id'][I]
这条线
df_sensor.loc[(df_sensor.user_id == labels_user_id) & (df_sensor.exp_id == labels_exp_id),'activity_id'].iloc[start:end]
返回此数据帧
我想更改特定索引中的user\u id和exp\u id所在的值(开始和结束)
编辑
我有两个数据帧
1:
2:
我想从DF2.activity\u id更改DF1的activity\u id,以开始和结束作为索引您的问题是链式分配:
df.loc[].iloc[]=
,它不会更改数据帧。无论选择多么复杂,您都希望更改仅在初始切片之后确定的值范围
我们可以定义您的初始掩码,并使用cumsum
进行一些数学运算,以允许使用单个.loc
调用进行相同的选择
样本数据
代码
您使用的是链式赋值
.loc[].iloc[]=
,因此尽管它不是典型的][
链接问题,结果仍然是你永远不会更改数据帧。你能提供更多的信息吗,比如你的索引是否重复,或者一些样本数据?有几种方法可以处理这个更复杂的选择。谢谢你的回答!我刚刚编辑了这个问题。我提供了一个答案,说明了问题,应该让您通过一些非常小的替换来解决。例如,您将使用m=(df\u sensor.user\u id==labels\u user\u id)&(df\u sensor.exp\u id==labels\u exp\u id)
和'activity\u id'
而不是'name'
。除非绝对必要,否则请不要将信息作为图像共享,这里不是这种情况。
name year value
0 A 2010 1
1 A 2011 2
2 B 2014 5
3 A 2012 3
4 A 2013 4
### Illustrate the problem
start = 1
end = 3
df.loc[df.name.eq('A'), 'name'].iloc[start:end] = 'foo'
# Nothing changes...
print(df)
# name year value
#0 A 2010 1
#1 A 2011 2
#2 B 2014 5
#3 A 2012 3
#4 A 2013 4
# Define your initial `.loc` condition
m = df.name.eq('A')
# Keep only True within the selection range. `where` logic allow for gaps.
m = (m.cumsum().gt(start) & m.cumsum().le(end)).where(m).fillna(False).astype(bool)
# Original df.loc[].iloc[] is a single selection:
df.loc[m, 'name'] = 'foo'
print(df)
# name year value
#0 A 2010 1
#1 foo 2011 2
#2 B 2014 5
#3 foo 2012 3
#4 A 2013 4