Home > front end >  Trying to make pandas python code shorter
Trying to make pandas python code shorter

Time:12-22

I'm fairly new to python and pandas. This code does exactly what I want it to do

dfmcomp=dfm.loc[dfm[ProgSel]=='C']
dfmcomp=dfmcomp[~dfmcomp.Code.isin(dfc.CourseCode)]
print(dfmcomp[['Code','Description']])

but I feel I should be able to do this in one line instead of three, and without creating an extra dataframe (dfmcomp). I'm trying to learn how to create better/neater code

I tried this to shorten it to two lines, by replacing dfmcomp in the second line with the code that created dfmcomp. I was hoping from there I could eliminate dfmcomp entirely and just print the sliced dfm, but it didn't work:

dfmcomp=dfm[~dfm.loc[dfm[ProgSel]=='C'].Code.isin(dfc.CourseCode)]
print(dfmcomp[['Code','Description']])

I got this error

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

And I am stuck where to go next. Can anyone help? Can this be done better?

CodePudding user response:

I think you should be able to do this?

print(dfm.loc[dfm[ProgSel].eq('C') & ~dfc.Code.isin(dfc.CourseCode), ['Code','Description']]

CodePudding user response:

    dfmcomp = dfm[(dfm.ProgSel == 'C') & (~dfm.Code.isin(dfc.CourseCode))][['Code', 'Description']]

    print(dfmcomp)

CodePudding user response:

Separating the condition into a mask might help:

mask = (dfm[ProgSel]=='C') & (~dfm.Code.isin(dfc.CourseCode))
print(dfm.loc[mask, ['Code','Description']])
  • Related