首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在pandas/python中编写函数

在pandas/python中编写函数
EN

Stack Overflow用户
提问于 2018-07-28 04:29:52
回答 2查看 55关注 0票数 0

我刚刚开始学习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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-28 04:32:06

我想你是在找np.where

df['exp']=np.where(df.str=='a',df['num']*-1,df['num']*1)
df
Out[281]: 
  str  num  num1  exp
0   a    1     3   -1
1   b    2     4    2
票数 1
EN

Stack Overflow用户

发布于 2018-07-28 04:41:30

正常数据帧操作:

df["exp"] = df.apply(lambda x: x["num"] * (1 if x["str"]=="a" else -1), axis=1)

数学数据帧操作:

df["exp"] = ((df["str"] == 'a')-0.5) * 2 * df["num"]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51565139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档