簡體   English   中英

根據數據框中另一列的值創建新列

[英]Create new column based on a value of another column in a data-frame

我當前數據框的一個片段是:

     |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]]

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

Output:

>>> 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

這對我有用:

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']))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM