![](/img/trans.png)
[英]Create a new column in Pandas Data-frame with a string value of a mask
[英]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 列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.