【问题标题】:how to create a dataframe from a nested for loop in python?如何从python中的嵌套for循环创建数据框?
【发布时间】:2019-12-30 08:25:44
【问题描述】:

如何从嵌套的 for 循环创建 pandas 数据框。在上面的问题中,我想创建一个我在那里打印的数据框。

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))

【问题讨论】:

  • 您的预期输出是什么?谢谢。
  • 输出:col1 col2 分数
  • col1 col2 score Country County 92 Country stats 17 Country PARK 18 Country cite 36 State County 18.....

标签: python python-3.x pandas python-2.7 dataframe


【解决方案1】:

使用append 创建列表并传递给DataFrame 构造函数:

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)])

或者使用列表推导:

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

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2021-12-08
    • 2023-03-27
    • 2017-10-15
    相关资源
    最近更新 更多