menu

Questions & Answers

Substring the value from another column into another using for loop pycharm but Why the result value always get the value from the last record

try to substring value from another column into another using for loop pycharm but the result value always get the value from the last record only

part of my code in pycharm

df = pd.DataFrame(data_2)

for index, row in df.iterrows():



txtype  = []



res=""

 num="0123456789"



for i in row['txmsg']:

if i in num:

break

else:

res+=i

txtype = res

df['txtype'] = txtype

print(df.head(100))

my expecting :

txtype values will containing the substring value from txmsg and it's defend on the value txmsg itself :

record 1 txmsg = ABCDEE_1234 then txtype will be ABCDEE_ record 2 txmsg = SAYANG_1234 then txtype will be SAYANG_ record 3 txmsg = BOLEHLAH_6789 then txtype will be BOLEHLAH_

results as per now

actually code is run and loop for each record, but value in txtype is always same like first record of loop (pls see picture for detail)

Answers(1) :

Here is another way by using a function to split the txmsg at '_', check if the end part is in num and if so returns the first part; if not in num then None is returned. This gives your required result.

def func(s):
    s1 = s.split('_')
    if s1[1] in num:
        return s1[0]+'_'
    else:
        return None
    
df['txtype'] = df['txmsg'].map(func)
Comments:
2023-01-22 00:30:02
I have tried but got 'IndexError: list index out of range' , in line ' if s1[1] in num:'