0

Before I start, my disclaimer is that I'm very new to Python and I've been building a flask app in an effort to learn more, so my question might be silly but please oblige me.

I have a Pandas Dataframe created from reading in a csv or excel doc on a flask app. The user uploads the document, so the dataframe and column names change with every upload.

The user also selects the columns they want to merge from a html multiselect object, which returns the selected columns from the user to the app script in the form of a python list.

What I currently have is:

df=pd.read_csv(file)
columns=df.columns.values

and

selected_col=request.form.getlist('columns')

All of this works fine, but I'm now stuck. How can I merge the values from the rows of this list of column names (selected_col) into a new column on the dataframe such that df["Merged"] = list of selected column values.

I've seen people use the merge function which seems to work well for 2 columns, but in this case it could be any number of columns that are merged, hence I'm looking for a function that either takes in a list of columns and merges it or iterates through the list of columns appending the values in a new column.

1 Answer 1

1

Sounds like what you want to do is more like an element-wise concatenation, not a merge.

If I understand you correctly, you can get your desired result with a list comprehension creating a nested list that is turned into a pandas Series by assigning it as a new DataFrame column:

df['Merged'] = [list(row) for row in df[selected_col].values]
Sign up to request clarification or add additional context in comments.

Comments

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.