Create a Series with both index and values equal to the index keys. Useful with map for returning an indexer based on an index. Parameters ---------- index : Index, optional Index of resulting Series. If None, defaults to original index.
(self, index=None, name: Hashable | None = None)
| 1647 | |
| 1648 | @final |
| 1649 | def to_series(self, index=None, name: Hashable | None = None) -> Series: |
| 1650 | """ |
| 1651 | Create a Series with both index and values equal to the index keys. |
| 1652 | |
| 1653 | Useful with map for returning an indexer based on an index. |
| 1654 | |
| 1655 | Parameters |
| 1656 | ---------- |
| 1657 | index : Index, optional |
| 1658 | Index of resulting Series. If None, defaults to original index. |
| 1659 | name : str, optional |
| 1660 | Name of resulting Series. If None, defaults to name of original |
| 1661 | index. |
| 1662 | |
| 1663 | Returns |
| 1664 | ------- |
| 1665 | Series |
| 1666 | The dtype will be based on the type of the Index values. |
| 1667 | |
| 1668 | See Also |
| 1669 | -------- |
| 1670 | Index.to_frame : Convert an Index to a DataFrame. |
| 1671 | Series.to_frame : Convert Series to DataFrame. |
| 1672 | |
| 1673 | Examples |
| 1674 | -------- |
| 1675 | >>> idx = pd.Index(["Ant", "Bear", "Cow"], name="animal") |
| 1676 | |
| 1677 | By default, the original index and original name is reused. |
| 1678 | |
| 1679 | >>> idx.to_series() |
| 1680 | animal |
| 1681 | Ant Ant |
| 1682 | Bear Bear |
| 1683 | Cow Cow |
| 1684 | Name: animal, dtype: str |
| 1685 | |
| 1686 | To enforce a new index, specify new labels to ``index``: |
| 1687 | |
| 1688 | >>> idx.to_series(index=[0, 1, 2]) |
| 1689 | 0 Ant |
| 1690 | 1 Bear |
| 1691 | 2 Cow |
| 1692 | Name: animal, dtype: str |
| 1693 | |
| 1694 | To override the name of the resulting column, specify ``name``: |
| 1695 | |
| 1696 | >>> idx.to_series(name="zoo") |
| 1697 | animal |
| 1698 | Ant Ant |
| 1699 | Bear Bear |
| 1700 | Cow Cow |
| 1701 | Name: zoo, dtype: str |
| 1702 | """ |
| 1703 | from pandas import Series |
| 1704 | |
| 1705 | if index is None: |
| 1706 | index = self._view() |