Data Conversion and Export Methods
After working with our Series, we may need to convert it into another format or save it somewhere.
to_list(): The to_list() method converts the Series into a Python list.
For example:
marks = pd.Series([85, 72, 90, 65])
marks.to_list()
output:
[85, 72, 90, 65]
to_numpy(): The to_numpy() method converts the Series into a NumPy array.
For example:
marks = pd.Series([85, 72, 90, 65])
marks.to_numpy()
output:
array([85, 72, 90, 65])
This is useful when we want to work with NumPy operations.
to_dict(): The to_dict() method converts the Series into a Python dictionary. The Series index becomes the dictionary key, and the Series values become the dictionary values.
For example:
marks = pd.Series([85, 72, 90], index=["A", "B", "C"])
marks.to_dict()
output:
{'A': 85, 'B': 72, 'C': 90}
to_frame(): The to_frame() method converts a Series into a DataFrame.
For example:
marks = pd.Series([85, 72, 90], name="Marks")
marks.to_frame()
output:
Marks
0 85
1 72
2 90
This is useful when we want to move from a one-dimensional Series structure to a two-dimensional DataFrame structure.
to_string(): The to_string() method converts the Series into a string representation.
For example:
marks = pd.Series([85, 72, 90])
marks.to_string()
output:
0 85
1 72
2 90
to_csv(): The to_csv() method exports the Series into a CSV file.
For example:
marks.to_csv("marks.csv")
Here, Pandas saves the Series data into a file named marks.csv.
to_json(): The to_json() method converts the Series data into JSON format.
For example:
marks.to_json()
output:
{"0":85,"1":72,"2":90}
We can also save it into a JSON file.
marks.to_json("marks.json")
Here, Pandas saves the Series data into a file named marks.json.