简体   繁体   English

熊猫-如何将不同的功能应用于df.series而该功能取决于另一个系列?

[英]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' ? 我怎样才能映射s1df.s2+1s1='a'和地图s1df.s2-1s1='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.

相关问题 使用另一个数组应用 function 如何在 pandas.Series 中使用参数 - Apply a function using another array how a argument in a pandas.Series 如何在pandas python中的isocalendar函数中应用系列 - How to apply series in isocalendar function in pandas python 类型错误:无法将系列转换为<class 'float'> / 如何将 pandas df 应用于类对象函数? - TypeError: cannot convert the series to <class 'float'> / How do I apply a pandas df to a class object function? 如何用 numpy 计算 df.Series 和 df.Series.shift(1) 之间的 corrcoef? - How to culculate the corrcoef between df.Series and df.Series.shift(1) with numpy? 如何有效地将 function 应用于大型 pandas 系列? - How to apply a function to a large pandas series efficiently? 将函数成对应用于熊猫系列 - Apply a function pairwise on a pandas series 如果值存在于另一个 df.Series 描述中,则从值列表中填充 pd.Series - Fill pd.Series from list of values if value exist in another df.Series description 如何将以系列为参数的函数应用于pandas列 - How to apply a function with series as argument to pandas column 熊猫:将函数应用于多索引系列 - Pandas: apply a function to a multiindexed series 如何在系列上应用功能 - How to apply a function on a Series
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM