dmnte
dmnte

Reputation: 65

performing function on values in dataframe and replacing

I want to perform a function on every value in a column of a pandas data frame and replace the old value with the new one. for example, going through every value in the column and replacing it with the value plus one. I have been trying things like the code below but it is not replacing the values.

for row in df["src"]:
    try:
            df["src"]= (function)
    except:
            print ("Error")

An example of column is below, all values are strings.

src

59.166.0.0
59.166.0.7
175.45.176.2
.
.
.
59.166.0.4

Upvotes: 2

Views: 852

Answers (2)

jezrael
jezrael

Reputation: 862581

I believe you need Series.apply:

df = pd.DataFrame({'src':['192.168.0.1','192.168.0.10', '']})
print (df)
            src
0   192.168.0.1
1  192.168.0.10
2              

def func(x):
    try:
        x = int(ipaddress.ip_address(x))
        return x
    except:
        return 0

df["src"] = df["src"].apply(func)
print (df)
          src
0  3232235521
1  3232235530
2           0

Upvotes: 3

U13-Forward
U13-Forward

Reputation: 71570

More none pandas solution:

def func(x):
    #code here
    return x

df["src"] = map(func,df['src'])

Or:

def func(x):
    #code here
    return x

df["src"] = [func(i) for i in df['src']]

Upvotes: 1

Related Questions