Given two Pandas Series, one containing names and the other containing corresponding scores, combine them into a single DataFrame to represent the data in tabular form.
Input: ["Jake", "Emily", "Harry"] and [85, 90, 78]
Output: Name Score
Jake 85
Emily 90
Harry 78
Let's explore different methods to combine two Pandas Series into a DataFrame.
Using pandas.concat()
pd.concat() concatenates Series along a specified axis. Using axis=1, series are combined column-wise; using axis=0, they are combined row-wise.
import pandas as pd
a = pd.Series(["Jake", "Emily", "Harry"])
b = pd.Series([85, 90, 78])
df = pd.concat([a, b], axis=1)
df.columns = ["Students", "Scores"]
print(df)
Output
Students Scores 0 Jake 85 1 Emily 90 2 Harry 78
Explanation: pd.concat([a, b], axis=1) combines the two series side by side. We then assign column names using df.columns.
Using merge()
pd.merge() is similar to SQL joins and can combine two series based on their indexes, creating a DataFrame with aligned data.
import pandas as pd
a = pd.Series(["Jake", "Emily", "Harry"], name="Students")
b = pd.Series([85, 90, 78], name="Scores")
df = pd.merge(a, b, left_index=True, right_index=True)
print(df)
Output
Students Scores 0 Jake 85 1 Emily 90 2 Harry 78
Explanation: pd.merge(a, b, left_index=True, right_index=True) joins the series using their index as a reference.
Using DataFrame.join()
join() combines two series by first converting one series into a DataFrame and then joining the other series as a column.
import pandas as pd
a = pd.Series(["Jake", "Emily", "Harry"], name="Students")
b = pd.Series([85, 90, 78], name="Scores")
df = a.to_frame().join(b)
print(df)
Output
Students Scores 0 Jake 85 1 Emily 90 2 Harry 78
Explanation: a.to_frame() converts the series into a DataFrame and join(b) adds the second series as a column.
Using dict inside DataFrame()
One can directly create a DataFrame from a dictionary of series, where keys become column names.
import pandas as pd
a = pd.Series(["Jake", "Emily", "Harry"])
b = pd.Series([85, 90, 78])
df = pd.DataFrame({"Students": a, "Scores": b})
print(df)
Output
Students Scores 0 Jake 85 1 Emily 90 2 Harry 78
Explanation: pd.DataFrame({"Students": a, "Scores": b}) directly maps series to columns, creating a clean DataFrame in a single step.