nskalis
nskalis

Reputation: 2382

how to replace a cell in a pandas dataframe

After forming the below python pandas dataframe (for example)

import pandas

data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pandas.DataFrame(data,columns=['Name','Age'])

If I iterate through it, I get

In [62]: for i in df.itertuples():
    ...:     print( i.Index, i.Name, i.Age )
    ...:     
0 Alex 10
1 Bob 12
2 Clarke 13

What I would like to achieve is to replace the value of a particular cell

In [67]: for i in df.itertuples():
    ...:     if i.Name == "Alex": 
    ...:         df.at[i.Index, 'Age'] = 100 
    ...:         

Which seems to work

In [64]: df
Out[64]: 
     Name  Age
0    Alex  100
1     Bob  12
2  Clarke  13

The problem is that when using a larger different dataset, and do:

First, I create a new column named like NETELEMENT with a default value of "" I would like to replace the default value "" with the string that the function lookup_netelement returns

df['NETELEMENT']    = ""
for i in df.itertuples():
            df.at[i.Index, 'NETELEMENT'] = lookup_netelement(i.PEER_SRC_IP)
            print( i, lookup_netelement(i.PEER_SRC_IP) )

But what I get as a result is:

Pandas(Index=769, SRC_AS='', DST_AS='', COMMS='', SRC_COMMS=nan, AS_PATH='', SRC_AS_PATH=nan, PREF='', SRC_PREF='0', MED='0', SRC_MED='0', PEER_SRC_AS='0', PEER_DST_AS='', PEER_SRC_IP='x.x.x.x', PEER_DST_IP='', IN_IFACE='', OUT_IFACE='', PROTOCOL='udp', TOS='0', BPS=35200.0, SRC_PREFIX='', DST_PREFIX='', NETELEMENT='', IN_IFNAME='', OUT_IFNAME='') routerX

meaning that it should be: NETELEMENT='routerX' instead of NETELEMENT=''

Could you please advise what I am doing wrong ?

EDIT: for reasons of completeness the lookup_netelement is defined as

def lookup_netelement(ipaddr):
    try:
        x = LOOKUP['conn'].hget('ipaddr;{}'.format(ipaddr), 'dev') or b""
    except:
        logger.error('looking up `ipaddr` for netelement caused `{}`'.format(repr(e)), exc_info=True)
        x = b""
    x = x.decode("utf-8")
    return x

Upvotes: 1

Views: 413

Answers (1)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Hope you are looking for where for conditional replacement i.e

def wow(x):    
    return x ** 10

df['new'] = df['Age'].where(~(df['Name'] == 'Alex'),wow(df['Age']))

Output :

      Name  Age           new
0    Alex   10   10000000000
1     Bob   12            12
2  Clarke   13            13
3    Alex   15  576650390625

Based on your edit your trying to apply the function i.e

df['new'] = df['PEER_SRC_IP'].apply(lookup_netelement)

Edit : For your comment on sending two columns, use lambda with axis 1 i.e

def wow(x,y):    
    return '{} {}'.format(x,y)

df.apply(lambda x : wow(x['Name'],x['Age']),1)

Upvotes: 3

Related Questions