我當前資料框的一個片段是:
|commentID | commentType |depth | parentID |
|:-------- |:-------------------------------:|
0 |58b61d1d | comment | 1.0 | 0.0 |
1 |58b6393b | userReply | 2.0 | 58b61d1d.0 |
2 |58b6556e | comment | 1.0 | 0.0 |
3 |58b657fa | userReply | 3.0 | 58b61d1d.0 |
4 |58b657fa | comment | 1.0 | 0.0 |
我希望資料框看起來像:
|commentID | commentType |depth | parentID | receiveAReply |
|:-------- |:--------------------------------|--------------:|
0 |58b61d1d | comment | 1.0 | 0.0 | 1 |
1 |58b6393b | userReply | 2.0 | 58b61d1d.0 | 0 |
2 |58b6556e | comment | 1.0 | 0.0 | 0 |
3 |58b657fa | userReply | 3.0 | 58b61d1d.0 | 0 |
4 |58b657fa | comment | 1.0 | 0.0 | 0 |
- 添加的列:receiveAReply
- 如果任何評論收到回復,則分配為 1。即使評論有多個回復,它仍然只分配 1 或 0。
- 所有用戶回復都會收到 0,即使該回復有回復,例如深度 = 3.0。這樣我只關心對實際文章的評論以及他們是否收到回復,而不是回復的數量或對這些回復的回復。
- 因此,我專注于深度 2.0 的用戶回復以及他們的 parentID 匹配的commentID。
我有以下代碼,但是它分配了整個receiveAReply 列Nan,我嘗試在其中創建另一列“回復”,其中它們具有深度為2.0 的父ID。我嘗試根據是否有任何commentID 與這些父ID 匹配來分配1:
df['replies'] = df.loc[df.depth == 2.0, ['parentID']]
df['receiveAReply'] = df.loc[df.commentID == df.replies, [1]]
uj5u.com熱心網友回復:
IIUC 您的條件,您只是錯過了提取parentID列的左側部分:
pid = df.loc[df['depth'] == 2, 'parentID'].str.split('.').str[0].values
df['receiveAReply'] = 0
df.loc[df['commentID'].isin(pid), 'receiveAReply'] = 1
輸出:
>>> df
commentID commentType depth parentID receiveAReply
0 58b61d1d comment 1.0 0.0 1
1 58b6393b userReply 2.0 58b61d1d.0 0
2 58b6556e comment 1.0 0.0 0
3 58b657fa userReply 3.0 58b61d1d.0 0
4 58b657fa comment 1.0 0.0 0
uj5u.com熱心網友回復:
這對我有用:
df['replies'] = df.loc[df.depth == 2.0, ['parentID']]
def test(x, y):
if x in y.values:
return 1
else:
return 0
df['getsReply'] = df['commentID'].apply(lambda x: test(x, df['replies']))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409849.html
標籤:
上一篇:如何從多索引資料框中估算Pandas資料框中的nan值?
下一篇:根據行中的值填充列
