0

I have this 3 lists on a Pandas DF:

            flat_values                          indexes                  tmp_values
[20, None, None, None, None, 30, 40]           [1, 2, 3, 4]            [40, 30, 10, 10]

What I want to do is to get a new field on my DF with a list consisting of the flat_values list and the tmp_values inserted at the position reflected in the indexes list numbers. So that:

               flat_values                          indexes                  tmp_values         new_values 
    [20, None, None, None, None, 30, 40]           [1, 2, 3, 4]            [40, 30, 10, 10]    [20, 40, 30, 10, 10, 30, 40] 

Thank you very much

4
  • 1
    What do you mean with index position? Both 20 for flat_values and 40 for tmp_values are position 0. Commented Jan 9, 2020 at 11:17
  • Sorry, I mean each number inside the "indexes" list Commented Jan 9, 2020 at 11:19
  • So do you mind to restate your question? Commented Jan 9, 2020 at 11:21
  • Done. I mean, for example, value 40 of tmp_values in position 1 (first value of indexes list) of flat_values list. Indexes and tmp_values lists always have the same length. Commented Jan 9, 2020 at 11:27

1 Answer 1

1

You can use apply,

def replace_val(row):
    l = row['flat_values'].copy()

    for i, m in zip(row['indexes'], row['tmp_values']):
        l[i] = m

    return l

df['new_values'] = df.apply(replace_val, axis=1)

Here is example,

a = [20, None, None, None, None, 30, 40]
b = [1, 2, 3, 4]
c = [40, 30, 10, 10]

d = [20, None, None, 30, 40]
e = [1, 2]
f = [100, 120]

df = pd.DataFrame({'flat_values': [a, d], 'indexes': [b, e], 'tmp_values': [c, f]})

def replace_val(row):
    l = row['flat_values'].copy()

    for i, m in zip(row['indexes'], row['tmp_values']):
        l[i] = m

    return l

df['new_values'] = df.apply(replace_val, axis=1)
print(df)

                            flat_values       indexes        tmp_values  \
0  [20, None, None, None, None, 30, 40]  [1, 2, 3, 4]  [40, 30, 10, 10]
1              [20, None, None, 30, 40]        [1, 2]        [100, 120]

                     new_values
0  [20, 40, 30, 10, 10, 30, 40]
1        [20, 100, 120, 30, 40]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for confirmation. I added copy() to the function because it also changes the values of flat_values. Maybe you want to change it. @FranG91

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.