Creating a Pandas df from two lists in python

Viewed 146

I have two python lists in following form:

A = [(1,''), (1, 'ABC'),(1,''), (1, 'DEF'),(1,''), (1, 'GHI'),(1,''), (1, 'LMO'),(1,'')]
B = ['ABC', 'ghi', 'PQR']

(Note: A is a list of list. B is normal list.)

I want to create a pandas DF that will only contain element that are common from both the lists and the form will be:

DF :
A     B
ABC   ABC
GHI   ghi 

Please note there might be lower case- upper case and also white spaces

5 Answers

Try:

t = [v for _, v in A if v in B]
df = pd.DataFrame({"A": t, "B": t})
print(df)

Prints:

     A    B
0  ABC  ABC
1  GHI  GHI

To handle upper/lower cases:

B = [v.upper() for v in B]
t = [v.upper() for _, v in A if v.upper() in B]
df = pd.DataFrame({"A": t, "B": t})
print(df)

you can try:

import numpy as np
a = np.intersect1d(np.array(A)[:,1], np.array(B))
df = pd.DataFrame({'A': a, 'B': a})

Input data:

>>> dfA
   _      A
0  1
1  1    AbC
2  1
3  1    DEF
4  1
5  1  G H I
6  1
7  1    LMO
8  1

>>> dfB
     B
0  ABC
1  GHI
2  PQR
>>> pd.merge(dfA, dfB,
             left_on=dfA["A"].str.upper().str.replace(' ', ''),
             right_on=dfB["B"].str.upper().str.replace(' ', ''))[["A", "B"]]
       A    B
0    AbC  ABC
1  G H I  GHI
import pandas as pd

A = [(1,''), (1, 'ABC'),(1,''), (1, 'DEF'),(1,''), (1, 'GHI'),(1,''), (1, 'LMO'),(1,'')]
B = ['ABC', 'GHI', 'PQR']

A = [i[1] for i in A if i[1] in B]
df = pd.DataFrame({'A':A,'B':A})
print(df)

to take care about case sensitivity and spaces try this:

import pandas as pd

A = [(1,''), (1, 'ABC'),(1,''), (1, 'DEF'),(1,''), (1, 'GHI'),(1,''), (1, 'LMO'),(1,'')]
B = ['ABC', 'GHI', 'PQR']

A = [i[1] for i in A if i[1].lower().replace(' ', '') in [x.lower().replace(' ','') for x in B]]
df = pd.DataFrame({'A': A, 'B': A})
 print(df)

Try:

t = [v for _, v in A if v in B]
df = pd.DataFrame({"A": t, "B": t})
print(df)

Prints:

     A    B
0  ABC  ABC
1  GHI  GHI

To handle upper/lower cases:

t = [v.upper() or v.lower() for _, v in A if v.upper() or or v.lower() in B]
df = pd.DataFrame({"A": t, "B": t})
print(df)
Related