【发布时间】:2019-03-10 17:19:44
【问题描述】:
我有一个案例,我试图以可理解的格式将计算出的百分比值附加到我的数据框中名为 df 的列中。当我说可理解的格式时,列中的输出应该类似于'40% Matched',如下例所示。
df = pd.DataFrame({ 'Col1':[['Phone', 'Watch', 'Pen', 'Pencil', 'Knife'],['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']], 'Col2': [['Phone', 'Watch', 'Pen', 'Pencil', 'fork'],['orange','avocado','kiwi','mango','grape','lemon','tomato']]})
df['Matched Percent'] = 'No Match'
for index,(lst1,lst2) in enumerate(zip(df['Col1'],df['Col2'])):
if(lst1 == lst2):
print('100% Matched')
else:
c1 = Counter(lst1)
c2 = Counter(lst2)
matching = {k: c1[k]+c2[k] for k in c1.keys() if k in c2}
text = '% Matched'
if len(lst1) > len(lst2):
out = round(len(matching)/len(lst1)*100)
#df['Matched Percent'].append(out,'% Matched')
print(out,'% Matched')
else:
out = round(len(matching)/len(lst2)*100)
#df['Matched Percent'].append(out,'% Matched')
print(out,'% Matched')
80 % Matched
62 % Matched
TypeError: cannot concatenate object of type "<class 'int'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid
我不断收到 TypeError。我尝试了几种方法,但没有运气。如上所示,我能够以我想要的方式在屏幕上打印值。但是当我将它附加到我的数据框df 时,它失败了。感谢有关如何解决此问题的建议。
【问题讨论】:
标签: python string python-3.x pandas typeerror