Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

pandas - searching if anyone of word is present in the another column of a dataframe or in another data frame using python

Hi I have two DataFrames like below

 DF1

 Alpha   |  Numeric  |  Special

 and     |  1        |   @
 or      |  2        |   $
         |  3        |   &  
         |  4        |     
         |  5        |     

and

DF2 with single column

Content      |

boy or girl  |
school @ morn|

I want to search if anyone of the column in DF1 has anyone of the keyword in content column of DF2 and the output should be in a new DF

 output_DF

 output_column|
 Alpha        |
 Special      |

someone help me with this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have a method that is not very good.

df1 = pd.DataFrame([[['and', 'or'],['1', '2','3','4','5'],['@', '$','&']]],columns=['Alpha','Numeric','Special'])    
print(df1)
       Alpha          Numeric    Special
0  [and, or]  [1, 2, 3, 4, 5]  [@, $, &]

df2 = pd.DataFrame([[['boy', 'or','girl']],[['school', '@','morn']]],columns=['Content'])    
print(df2)
             Content
0    [boy, or, girl]
1  [school, @, morn]

First, combine the df2 data:

df2list=[x for row in df2['Content'].tolist() for x in row]
print(df2list)
['boy', 'or', 'girl', 'school', '@', 'morn']

Then get data of each column of df1 is intersected with the df2list:

containlistname = []
for i in range(0,df1.shape[1]):
    columnsname = df1.columns[i]
    df1list=[x for row in df1[columnsname].tolist() for x in row]
    intersection = list(set(df1list).intersection(set(df2list)))
    if len(intersection)>0:
        containlistname.append(columnsname)
output_DF = pd.DataFrame(containlistname,columns=['output_column'])

Final print:

print(output_DF)
  output_column
0         Alpha
1       Special

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...