[英]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.