简体   繁体   中英

Python pandas ISIN with variable

I could use a hand on using the ISIN pandas function. Basically, I need to aggregate data in a dataframe according to different criteria by year. The issue is that I need to do many aggregations on the data (eg country name, funding program, etc.). To make it expedient I am trying to do this in for loops. A simplified example below:

Here I am trying to create a list for each country and pair of programs (ProgA or ProgB).

aux = EABlock.loc[EABlock["Country"].isin([Ctry]) & EABlock["FundingSource"].isin([Prog]),["2020","2021","2022","2023","2024","2025","2026","2027","2028"]].agg(sum)

Where Prog = ['ProgA', 'ProgB']

and I get this wrong result (all zeroes):

2021    0.0
2022    0.0
2023    0.0
2024    0.0
2025    0.0
2026    0.0
2027    0.0
2028    0.0

When instead I write

aux = EABlock.loc[EABlock["Country"].isin([Ctry]) & EABlock["FundingSource"].isin(["ProgA", "ProgB"]),["2020","2021","2022","2023","2024","2025","2026","2027","2028"]].agg(sum)

I get the correct result:

2020      3.000000
2021    323.216667
2022    127.533333
2023      1.500000
2024   -148.000000
2025    -25.083333
2026    -48.133333
2027   -234.033333
2028      0.000000

Further puzzling me is the fact that the criteria seem to be exactly the same:

Prog
Out[50]: ['ProgA', 'ProgB']

["ProgA", "ProgB"]
Out[51]: ['ProgA', 'ProgB']

What am I doing wrong?

No, it is not same, if pass list to list then ouput are nested list:

EABlock["FundingSource"].isin([Prog])

it is same like:

EABlock["FundingSource"].isin([["ProgA", "ProgB"]])

But you want pass list without [] :

EABlock["FundingSource"].isin(Prog)

It is same like:

EABlock["FundingSource"].isin(["ProgA", "ProgB"])

See here's the problem, In the first snippet, you are passing [Prog] to isin(), and it is different from passing ["ProgA", "ProgB"] as in the second snippet.

在此处输入图像描述

The solution is to pass Prog without [] .

Thank you:)

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