1

I have a DataFrame with two columns that look something like this:

 A B 0 '_______' [2,3] 1 '_______' [0] 2 '_______' [1,4,6] 

where one column is a string with 7 "_" and the other column contains a numpy array with different lengths. My goal is to change column A using B as indexes so it looks like this:

 A B 1 '__23___' [2,3] 2 '0______' [0] 3 '_1__4_6' [1,4,6] 

My code seems to work but I keep getting the error:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.

I don't understand how I fix this error. My code is:

for i in range(len(df)): row = df.iloc[i,:].copy() numbers = row['B'] for j in numbers: loop_string = df['A'][i] df['A'][i] = loop_string[:j] + str(j) + loop_string[j+1:] 

Also the fact that I need two for loops bothers me this must be possible an other more efficient way. Can anyone help me?

1 Answer 1

1

You can use apply to use a custom function on the B column:

df['A'] = df['B'].apply(lambda l: ''.join([str(i) if i in l else '_'for i in range(7)])) 

The above does not consider the original value of A but instead creates an entirely new string column.

Result:

 A B 0 __23___ [2, 3] 1 0______ [0] 2 _1__4_6 [1, 4, 6] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.