1
$\begingroup$

The last time I used Python is some time ago so some things have faded away.

I have a given dataset, with multiple columns. I want to create a new column and set the values based on multiple values (text or value) of other columns.

So in the example below, c1 consists of [a,a,b,b] and c2 of [a,b,a,b]. Now I want the new column c3 to be [1,2,3,4]

All help is appreciated!

import pandas as pd
data = pd.read_excel('data')

data['c3'] = 0

for i in range(len(data.c3)):
    if data.c1[i] == a and data.c2[i] == a:
        data.c3[i] == 1
    elif data.c1[i] == a and data.c2[i] != a:
        data.c3[i] == 2
    elif data.c1[i] != a and data.c2[i] == a:
        data.c3[i] == 3
    elif data.c1[i] != a and data.c2[i] != a:
        data.c3[i] == 4```

$\endgroup$

1 Answer 1

1
$\begingroup$

I would use apply. It allows you to perform a function row-wise or column-wise. Check this post on StackOverflow, it provides good examples of what this looks like.

The gist is:

  • create a function that creates the value you want based on a row
  • use apply to create a dataframe containing the results
  • if you're happy with the results, merge that dataframe into your existing one
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.