简体   繁体   中英

How to get the index as a value, not a tuple from a pandas series

I have a pandas series called valueCounts:

In: valueCounts
Out[58]: 
StartDate 
1986-01-02      22
1986-01-03      25
1986-01-06      26
1986-01-07      28
1986-01-09      29
              ... 
2022-07-06    1947
2022-07-11    1948
2022-07-14    1949
2022-07-18    1951
2022-07-22    1952
Length: 680, dtype: int64

I can get the index as a list of tuples:

In: valueCounts.index
Out[59]: 
MultiIndex([('1986-01-02',),
            ('1986-01-03',),
            ('1986-01-06',),
            ('1986-01-07',),
            ('1986-01-09',),
            ('1987-09-01',),
            ('1987-09-10',),
            ('1988-09-13',),
            ('1988-10-26',),
            ('1989-10-26',),
            ...
            ('2022-06-20',),
            ('2022-06-21',),
            ('2022-06-28',),
            ('2022-07-01',),
            ('2022-07-04',),
            ('2022-07-06',),
            ('2022-07-11',),
            ('2022-07-14',),
            ('2022-07-18',),
            ('2022-07-22',)],
           names=['StartDate'], length=680)

How can I get that list of tuples as a list of Timestamps or String, or whatever, just not tuples?

Here is an example of how to do it:

import pandas as pd

valueCounts = pd.DataFrame(
    {
        "StartDate": [
            "2022-01-01",
            "2022-01-02",
            "2022-01-03",
            "2022-01-02",
            "2022-01-03",
            "2022-01-02",
            "2022-01-03",
            "2022-01-01",
            "2022-01-01",
            "2022-01-01",
        ]
    }
).value_counts()

print(valueCounts)
# Output
StartDate 
2022-01-01    4
2022-01-02    3
2022-01-03    3
dtype: int64
indices = valueCounts.index.get_level_values(0).to_list()

print(indices)
# Output
['2022-01-01', '2022-01-02', '2022-01-03']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM