Josh
Josh

Reputation: 75

How to take the first character from every item in a list and manipulate it

My code is the following:

manipulate_list = data['Incorrect Frequency Cap1'].astype(str).tolist()
manipulate_list = ['Blank' if x == '' else x for x in manipulate_list]

first_numerical = []
for i in manipulate_list:
    first_numerical.append(i[0])

completed_frequency = []
for i in first_numerical:
    if i == 'N':
        completed_frequency.append(i+ 'o Cap Per Day')
    if i == 'B':
        completed_frequency.append(i+'lank')
    else:
        completed_frequency.append(i+' x Per Day') 

When I check "first_numerical" with the following - first_numerical[5] - I get '5'.

Why am I getting the following when I check "completed_frequency"?

completed_frequency[5] = 'N x Per Day'

Upvotes: 2

Views: 181

Answers (2)

M_S_N
M_S_N

Reputation: 2810

IIUC, your list kind of gets overwritten as you missed elif do this

  for i in first_numerical:
        if i == 'N':
            completed_frequency.append(i+ 'o Cap Per Day')
        elif i == 'B':
            completed_frequency.append(i+'lank')
        else:
            completed_frequency.append(i+' x Per Day')

Lets have an example to clear the air

n=['1','1','1']
b=[]
for i in n:
    if i == '1':
        b.append(i)
    if i=='2':
        b.append(2)
    else:
        b.append('none')

Output

['1', 'none', '1', 'none', '1', 'none']

Correct way

n=['1','1','1']
b=[]
for i in n:
    if i == '1':
        b.append(i)
    elif i=='2':
        b.append(2)
    else:
        b.append('none')

Output

['1', '1', '1']

Not overwritten but gets appended with extra values

Upvotes: 3

sirius
sirius

Reputation: 20

Maybe you can try this, function isnumeric return True if all characters in string are numeric.

 for i in first_numerical:
    if i == 'N':
        completed_frequency.append(i+ 'o Cap Per Day')
    if i == 'B':
        completed_frequency.append(i+'lank')
    if (i.isnumeric()):
        completed_frequency.append(i+' x Per Day') 

Upvotes: 0

Related Questions