我有数据框'dfm':
match group
adamant 86
adamant 86
adamant bild 86
360works 94
360works 94
在“组”列相同的地方,我想将“匹配”列的内容两两比较,然后将比较结果添加到另一列“结果”中。例如,预期结果将是:
group compare result
86 adamant, adamant same
86 adamant, adamant bild not same
86 adamant, adamant bild not same
94 360works,360works same
有人可以帮忙吗?
有点骇人听闻,但似乎对我有用:
# initialize the list to store the dictionaries
# that will create the new DataFrame
new_df_dicts = []
# group on 'group'
for group, indices in dfm.groupby('group').groups.iteritems():
# get the values in the 'match' column
vals = dfm.ix[indices]['match'].values
# choose every possible pair from the array of column values
for i in range(len(vals)):
for j in range(i+1, len(vals)):
# compute the new values
compare = vals[i] + ', ' + vals[j]
if vals[i] == vals[j]:
result = 'same'
else:
result = 'not same'
# append the results to the DataFrame
new_df_dicts.append({'group': group, 'compare': compare, 'result': result})
# create the new DataFrame
new_df = DataFrame(new_df_dicts)
这是我的输出:
compare group result
0 360works, 360works 94 same
1 adamant, adamant 86 same
2 adamant, adamant bild 86 not same
3 adamant, adamant bild 86 not same
以前,我建议将行附加到初始化的DataFrame中。从字典列表中创建一个DataFrame而不是对DataFrame进行许多追加操作,运行速度快9-10倍。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句