Comparing Python Lists to Data Frames

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

List result_stopWords[0]

['pms', 'change']

Data frame df_freqOrg[0]

     keywords   cnt
0   and         484 
1   pms         409 
2   to          378 
3   change      350 

Compare the list and the data frame result

    keywords   cnt
0  pms         409
1  change      350

I want to make it like this. What should I do?

I'm doing Python's Pandas.

python

2022-09-20 11:13

2 Answers

You can use isin.

>>> import pandas as pd
>>> df = pd.DataFrame({"keyword":[ "and", "pms", "to", "change" ],
           "cnt":[484, 409, 378, 350]})
>>> df
  keyword  cnt
0     and  484
1     pms  409
2      to  378
3  change  350


>>> df[df["keyword"].isin(["pms", "change"])]
  keyword  cnt
1     pms  409
3  change  350
>>> df[df["keyword"].isin(["pms", "change"])].reset_index(drop=True)
  keyword  cnt
0     pms  409
1  change  350


2022-09-20 11:13

Add another method.

>>> selected_names = ["pms", "change"]
>>> df.set_index("keyword").loc[selected_names ]
         cnt
keyword     
pms      409
change   350
>>> df.set_index("keyword").loc[selected_names ].reset_index()
  keyword  cnt
0     pms  409
1  change  350


2022-09-20 11:13

If you have any answers or tips


© 2022 pinfo. All rights reserved.