gpt4 book ai didi

python - Pandas - 在 applymap 期间获取每个元素的行和列名称

转载 作者:太空狗 更新时间:2023-10-29 22:12:29 25 4
gpt4 key购买 nike

我正在尝试比较一个字符串列表的相似性,并在 pandas 数据框中获取结果以供检查;所以我使用一个列表作为索引,另一个作为列列表。然后我想计算它们的“Levenshtein 相似度”(一个比较两个词之间相似度的函数)。

我尝试在每个单元格上使用 applymap 来做到这一点,并将单元格索引与单元格列进行比较。我怎么能那样做?或者更简单的替代方案?

things = ['car', 'bike', 'sidewalk', 'eatery']
action = ['walking', 'caring', 'biking', 'eating']
matrix = pd.DataFrame(index = things, columns = action)

def lev(x):
x = Levenshtein.distance(x.index, x.column)
matrix.applymap(lev)

到目前为止,我使用了以下(下方),但我发现它笨拙且缓慢

matrix = pd.DataFrame(data = [action for i in things], index = things, columns = action)
for i, values in matrix.iterrows():
for j, value in enumerate(values):
matrix.ix[i,j] = Levenshtein.distance(i, value)

最佳答案

我想你可以使用 apply在数据框上,并使用 .name 访问列的值:

def lev(x):
#replace your function
return x.index + x.name
a = matrix.apply(lev)
print (a)
walking caring biking eating
car carwalking carcaring carbiking careating
bike bikewalking bikecaring bikebiking bikeeating
sidewalk sidewalkwalking sidewalkcaring sidewalkbiking sidewalkeating
eatery eaterywalking eaterycaring eaterybiking eateryeating

编辑:

如果需要一些算术运算使用broadcasting :

a = pd.DataFrame(matrix.index.values + matrix.columns.values[:,None], 
index=matrix.index,
columns=matrix.columns)
print (a)
walking caring biking eating
car carwalking bikewalking sidewalkwalking eaterywalking
bike carcaring bikecaring sidewalkcaring eaterycaring
sidewalk carbiking bikebiking sidewalkbiking eaterybiking
eatery careating bikeeating sidewalkeating eateryeating

或者:

a = pd.DataFrame(matrix.index.values + matrix.columns.values[:, np.newaxis], 
index=matrix.index,
columns=matrix.columns)
print (a)
walking caring biking eating
car carwalking bikewalking sidewalkwalking eaterywalking
bike carcaring bikecaring sidewalkcaring eaterycaring
sidewalk carbiking bikebiking sidewalkbiking eaterybiking
eatery careating bikeeating sidewalkeating eateryeating

关于python - Pandas - 在 applymap 期间获取每个元素的行和列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com