如何根据其他两个列中的条件创建和填充新列?
如何根据另外两个列的条件创建一个新列并用值填充值?
输入:
import pandas as pd
import numpy as np
list1 = ['no','no','yes','yes','no','no','no','yes','no','yes','yes','no','no','no']
list2 = ['no','no','no','no','no','yes','yes','no','no','no','no','no','yes','no']
df = pd.DataFrame({'A' : list1, 'B' : list2}, columns = ['A', 'B'])
df['C'] = np.where ((df['A'] == 'yes') & (df['A'].shift(1) == 'no'), 'X', np.nan)
df['D'] = 'nan','nan','X','X','X','X','nan','X','X','X','X','X','X','nan'
print (df)
输出:
A B C D
0 no no nan nan
1 no no nan nan
2 yes no X X
3 yes no nan X
4 no no nan X
5 no yes nan X
6 no yes nan nan
7 yes no X X
8 no no nan X
9 yes no X X
10 yes no nan X
11 no no nan X
12 no yes nan X
13 no no nan nan
A和B列将是Givens,仅包含“是”或“否”值。只能有三对('no' - 'no','yes' - 'no'或'no' - 'YES')。永远不可能有“是” - “是”对。
目的是在遇到“是” - “否”对时,将“ X”放在新列中,然后继续填充'X,直到有“否” - '是'是'对。这可能会在几行或几百行中发生。
D列显示了所需的输出。
C列是当前失败的尝试。
谁能帮忙?提前致谢。
How can I create a new column and fill it with values based on the condition of two other columns?
input:
import pandas as pd
import numpy as np
list1 = ['no','no','yes','yes','no','no','no','yes','no','yes','yes','no','no','no']
list2 = ['no','no','no','no','no','yes','yes','no','no','no','no','no','yes','no']
df = pd.DataFrame({'A' : list1, 'B' : list2}, columns = ['A', 'B'])
df['C'] = np.where ((df['A'] == 'yes') & (df['A'].shift(1) == 'no'), 'X', np.nan)
df['D'] = 'nan','nan','X','X','X','X','nan','X','X','X','X','X','X','nan'
print (df)
output:
A B C D
0 no no nan nan
1 no no nan nan
2 yes no X X
3 yes no nan X
4 no no nan X
5 no yes nan X
6 no yes nan nan
7 yes no X X
8 no no nan X
9 yes no X X
10 yes no nan X
11 no no nan X
12 no yes nan X
13 no no nan nan
Columns A and B will be givens and only contain 'yes' or 'no' values. There can only be three possible pairs ('no'-'no', 'yes'-'no', or 'no'-'yes'). There can never be a 'yes'-'yes' pair.
The goal is to place an 'X' in the new column when a 'yes'-'no' pair is encountered and then to continue filling in 'X's until there is a 'no'-'yes' pair. This could happen over a few rows or several hundred rows.
Column D shows the desired output.
Column C is the current failing attempt.
Can anyone help? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试以下操作:
结果:
Try this:
Results:
您可以使用Apply()来做到这一点,
您的功能可能是:
You can use apply() to do that,
Where your functions can be:
您可以这样尝试。在这里,我使用
iTerrows
在行上循环you can try this way. Here, I use
iterrows
to loop over rows这将完成工作,
输出 -
This would get the job done,
Output -