1

How can i create pandas dataframe from a nested for loop.In the above question i want to create a dataframe of what i am printing over there.

df:
    col1     col2
0   Country   County
1   State     stats
2   City      PARK
3   park      parking
4   site      Cite
from fuzzywuzzy import fuzz
for i in df.col1:
  for j in df.col2:    
    print(i,j,fuzz.token_set_ratio(i,j))
3
  • What is your expected output? Thank you. Commented Dec 30, 2019 at 8:28
  • Output: col1 col2 score Commented Dec 30, 2019 at 8:38
  • col1 col2 score Country County 92 Country stats 17 Country PARK 18 Country cite 36 State County 18..... Commented Dec 30, 2019 at 8:40

1 Answer 1

2

Create list with append and pass to DataFrame constructor:

from fuzzywuzzy import fuzz
L = []
for i in df.col1:
  for j in df.col2:    
    L.append([i,j,fuzz.token_set_ratio(i,j)])

Or use list comprehension:

from fuzzywuzzy import fuzz
L = [[i,j,fuzz.token_set_ratio(i,j)] for i in df.col1 for j in df.col2]

df = pd.DataFrame(L, columns=['col1','col2','score'])
print (df)
       col1     col2  score
0   Country   County     92
1   Country    stats     17
2   Country     PARK     18
3   Country  parking     14
4   Country     Cite     36
5     State   County     18
6     State    stats     80
7     State     PARK     22
8     State  parking     17
9     State     Cite     44
10     City   County     60
11     City    stats     22
12     City     PARK      0
13     City  parking     18
14     City     Cite     75
15     park   County      0
16     park    stats     22
17     park     PARK    100
18     park  parking     73
19     park     Cite      0
20     site   County     20
21     site    stats     44
22     site     PARK      0
23     site  parking     18
24     site     Cite     75
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.