假设我有如下所示的df1和df2:
df1:
start end group
index
a 1 3 x
a 3 6 x
a 6 9 z
b 1 7 y
b 7 15 x
b 15 17 y
c 1 4 z
c 4 9 z
c 9 15 z
df2:
value
index
a 1.0
a 4.8
a 7.0
b 2.0
b 5.0
b 6.0
c 2.0
c 3.0
c 14.0我想在df2中创建一个名为group的新列,并根据将df2.value引用到df1.start和df1.end的条件为其赋值,例如:
if df2.value >= df1.start and df2.value < df1.end:
df2.group = df1.group例如,在索引'a‘中,范围1-3=x;3-6=x;6-9=z,在索引'b’中,范围1-7=y;7-15=x;15-17=y,在索引'c‘中,范围1-4=z;4-9=z;9-15=z
所以结果会是这样的:
df2:
value group
index
a 1.0 x
a 4.8 x
a 7.0 z
b 2.0 y
b 5.0 y
b 6.0 y
c 2.0 z
c 3.0 z
c 14.0 z我如何才能做到这一点?
发布于 2020-07-06 16:00:09
假设两个数据帧具有相同的长度,您可以使用np.where轻松实现这一点
np.where((df2.value>=df1.start) & (df2.value<df1.end), df2.group=df1.group, df2.group=0)这将评估您的条件,如果为False,则将df2.group设置为0。
发布于 2020-07-06 16:01:21
尝试以下方法:
list_in = []
for i in range(0, df2.shape[0]):
if df1.iloc[i]['start']<=df2.iloc[i]['value']<df1.iloc[i]['end']:
list_in.append(df1.iloc[i]['group'])
else:
list_in.append('Nan')
df2 = df2.assign(group = list_in)https://stackoverflow.com/questions/62751576
复制相似问题