I have a pandas dataframe with the following columns:
Looks like this:
Product New York California
Widget01 100 50
I want to reshape the frame using the two location columns to create a new column like this:
Product Location Total Sold
Widget01 New York 100
Widget01 California 50
How does one achieve this with pandas?
When working with data using Pandas, you may need to combine two columns in Pandas to create another column. You can combine two columns in Pandas using df [“new column name“] = df [“column 1”] + df ["column 2”] statement. In this tutorial, you’ll learn how to combine or concatenate two or more columns in Pandas dataframe to create another column.
You can use the following syntax to combine two text columns into one in a pandas DataFrame: df[' new_column '] = df[' column1 '] + df[' column2 '] If one of the columns isn’t already a string, you can convert it using the astype(str) command: df[' new_column '] = df[' column1 ']. astype (str) + df[' column2 ']
Pandas .join (): Combining Data on a Column or Index. While merge () is a module function, .join () is an object function that lives on your DataFrame. This enables you to specify only one DataFrame, which will join the DataFrame you call .join () on.
It is possible to join the different columns is using concat () method. Syntax: pandas.concat (objs: Union [Iterable [‘DataFrame’], Mapping [Label, ‘DataFrame’]], axis=’0′, join: str = “‘outer'”) DataFrame: It is dataframe name. axis: 0 refers to the row axis and1 refers the column axis. join: Type of join.
You can use pandas.melt()
-
pd.melt(df,id_vars='Product', var_name='Location',value_name='Total Sold')
Demo -
In [72]: df
Out[72]:
Product New York California
0 Widget01 100 50
In [73]: pd.melt(df,id_vars='Product', var_name='Location',value_name='Total Sold')
Out[73]:
Product Location Total Sold
0 Widget01 New York 100
1 Widget01 California 50
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With