python pandas写入_在pandas / python中写入函数

我刚开始学习python并且没有太多的开发背景。这是我在学习时编写的代码。

我现在想要创建一个与我的“for”循环正在做的功能但它需要根据不同的num(num,num1等)计算不同的exp(exp,exp1等)的函数

我怎样才能做到这一点?import pandas as pd

index = [0,1]

s = pd.Series(['a','b'],index= index)

t = pd.Series([1,2],index= index)

t1 = pd.Series([3,4],index= index)

df = pd.DataFrame(s,columns = ["str"])

df["num"] =t

df['num1']=t1

print (df)

exp=[]

for index, row in df.iterrows():

if(row['str'] == 'a'):

row['mul'] = -1 * row['num']

exp.append(row['mul'])

else:

row['mul'] = 1 * row['num']

exp.append(row['mul'])

df['exp'] = exp

print (df)

这就是我试图做的错误结果import pandas as pd

index = [0,1]

s = pd.Series(['a','b'],index= index)

t = pd.Series([1,2],index= index)

t1 = pd.Series([3,4],index= index)

df = pd.DataFrame(s,columns = ["str"])

df["num"] =t

df['num1']=t1

def f(x):

exp=[]

for index, row in df.iterrows():

if(row['str'] == 'a'):

row['mul'] = -1 * x

exp.append(row['mul'])

else:

row['mul'] = 1 * x

exp.append(row['mul'])

return exp

df['exp'] = df['num'].apply(f)

df['exp1'] = df['num1'].apply(f)

df

根据以下建议,我会这样做:df['exp']=np.where(df.str=='a',df['num']*-1,df['num']*1)

df['exp1']=np.where(df.str=='a',df['num1']*-1,df['num1']*1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值