0

I have this dataframe:

df = pd.DataFrame({'A': {0: '1',  1: '2',  2: '4',  3: '7',  4: '7'},
 'B': {0: 'S', 1: 'S', 2: 'D', 3: 'D', 4: 'S'},
 'C': {0: 'XX',  1: 'WX',  2: 'WX',  3: 'XX',  4: 'XW'},
 'Location': {0: '32',  1: '63',  2: '32',  3: '42',  4: '42'}})

enter image description here

And I created this function:

def Transformation(df_, col_names):
    # function code (irrelevant for the problem statement)
    df_.groupby([col_names,"Location"]) # the line problem
    # function code (irrelevant for the problem statement)
    return df_ # (irrelevant for the problem statement)

Transformation(z, ["A", "B"]) # How you call the function. col_names has to be more than 1.

# the line problem above: How can I concatenate col_names with "Location" in the groupby argument? You can assume that dimensions is always given as a list of strings with more of one element, just like this:

Transformation(df, ["A", "B"])
Transformation(df, ["C", "A"])
Transformation(df, ["A", "B", "C", "D"]) # You can assume that the whole abecedary is in the columns of `df` and you can combine them as you wish, but for minimal example purposes I think two is enough

"Location" cannot go inside the dimensions arguments (for the function purposes), if you do so the function will raise an error. So, assume that "Location" never goes in the input arguments but rather it's added somewhere in the function code, and when I'm adding "Location" is where I'm having the problem.

One of the approaches I used and I don't understand why is not working:

df_.groupby(col_names.append("Location"))

Which led me to:

x = ["A","B", "C"]
x_aux = x.append("Location")
x_aux # gives "None"

BUT!:

x = ["A","B", "C"]
x.append("Location")
x # gives ["A","B", "C", "Location"]

Why does that happen? Any suggestions to concatenate it inside the groupby function?

1 Answer 1

2

you can put Location in a list and use "+" to concat the lists.

df_.groupby(col_names+["Location"])
Sign up to request clarification or add additional context in comments.

2 Comments

Well, that was pretty straightforward. Do you know why the example I gave x_aux = x.append("Location") gives None?
@Chris, the append function changes the list x but returns None. That's why when you assign x.append(...) to x_aux, x_aux is None because the new element is directly appended to x.

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.