【发布时间】:2020-02-02 03:33:40
【问题描述】:
与Get column value if it matches another column value in the same table 相同,但使用 Python/pandas 而不是使用 SQL,因为查询运行时间太长。
我有一个 df:
Id | replyId | commentID_parentID | usernameChannelId | channelId
1 | NULL | NULL | a | g
2 | NULL | NULL | b | k
NULL | 1.k | 1 | a | p
NULL | 1.p | 1 | c | i
3 | NULL | NULL | d | h
NULL | 2.k | 2 | g | g
还有一个带有如下频道的表格:
我想知道哪个用户(userChannelId)回复了哪个用户。
所以我在评论中排了一行并检查是否:
Id == NULL? Then it's a reply -> get userChannelId where commentID_parentID == Id
Id != NULL? Then it's a main comment -> userChannelId replied to channelId
结果应该是:
userChannelId_Source | userChannelId_Target
a | g
b | k
a | a
c | a
g | b
评论“d”没有commentID_parentID == Id的条目,因此被省略了。
到目前为止我的代码:
cm["usernameChannelId_reply"] = None
for row in cm.itertuples():
if cm.commentID_parentID is None: # comment is a main comment
cm.at[row.Index, 'usernameChannelId_reply'] = cm.channelId
else: # comment is a reply comment
temp = cm.loc[cm.Id == row.commentID_parentID]["usernameChannelId"][0]
#temp = cm.query("Id == commentID_parentID").head(1).loc[:, 'usernameChannelId']
print(temp)
if len(set(temp)) == 0:
print(0, row.Index)
#cm.at[row.Index, 'usernameChannelId_reply'] = temp
else:
cm.at[row.Index, 'usernameChannelId_reply'] = temp
但我得到了一个
密钥错误:0
删除 [0] 打印例如:
997 UCOYb6iKhuCHKDwvd_iBnIBw 名称:usernameChannelId,dtype:object
【问题讨论】:
-
你说“d”被省略了,但我看不出这一行和前两行有什么区别?
-
“这一行”是指哪一行?
-
usernameChannelId中带d的行的结构看起来像第一行,为什么去掉d的行?
-
如果在 SQL 中需要很长时间,我怀疑它在 Python 中会更快。您优化了数据/表/查询吗?