[英]pandas-how to apply different function to df.series while the function depending on another series?
Simply speaking, I want to do this: 简单来说,我想这样做:
df.s1.map["a":df.s2+1, "b":df.s2-1]
However,it won't work because df.s2
is not a constant. 但是,由于
df.s2
不是常数,因此无法使用。
How can I map s1
on df.s2+1
while s1='a'
,and map s1
on df.s2-1
while s1='b'
? 我怎样才能映射
s1
上df.s2+1
而s1='a'
和地图s1
上df.s2-1
而s1='b'
You can use apply
using lambda
with axis = 1
ie 您可以使用
axis = 1
lambda
使用apply
if you have a dataframe 如果您有数据框
df = pd.DataFrame({'s1':['a','b','a','a','b'],'s2':[1,3,5,2,4]})
df['s3'] = df.apply(lambda x : x['s2']+1 if x['s1'] == 'a' else x['s2']-1 ,axis=1 )
Or take d['s2'] common from the dictionary and then add it at the end after mapping. 或从字典中选取d ['s2']公用,然后在映射后将其添加到末尾。
df['s3'] = df.s1.map({'a':1,'b':-1})+df['s2']
Output: 输出:
s1 s2 s3 0 a 1 2 1 b 3 2 2 a 5 6 3 a 2 3 4 b 4 3 In [364]:
Output : 输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.