barciewicz
barciewicz

Reputation: 3793

Pandas: create two lists from single Series in a single operation

Is it possible to create lists as above in a single operation, so as not to have to iterate over printedPGDate twice?

    #months list
    months = list(set(df['printedPGDate'].map(lambda date : date.month)))
    print(months)

    #years list
    years = list(set(df['printedPGDate'].map(lambda date : date.year)))
    print(years)

Upvotes: 1

Views: 33

Answers (1)

jezrael
jezrael

Reputation: 863031

I think not easy way, you can also use:

months = df['printedPGDate'].dt.month.unique().tolist()
years = df['printedPGDate'].dt.year.unique().tolist()

If want loop only once is possible create defaultdict:

rng = pd.date_range('2017-04-03', periods=10, freq='400D')
df = pd.DataFrame({'printedPGDate': rng, 'a': range(10)})  
print (df)
  printedPGDate  a
0    2017-04-03  0
1    2018-05-08  1
2    2019-06-12  2
3    2020-07-16  3
4    2021-08-20  4
5    2022-09-24  5
6    2023-10-29  6
7    2024-12-02  7
8    2026-01-06  8
9    2027-02-10  9

from collections import defaultdict

d = defaultdict(list)

for x in df['printedPGDate']:
    d['months'].append(x.month)
    d['years'].append(x.year)

print (d)
defaultdict(<class 'list'>, {'months': [4, 5, 6, 7, 8, 9, 10, 12, 1, 2], 
                             'years': [2017, 2018, 2019, 2020, 2021, 
                                       2022, 2023, 2024, 2026, 2027]})

Upvotes: 1

Related Questions