[英]Is there a way to assign number of incremental value in a new column of each rows based current and previous row values of existing columns?
I have a dataframe, df and I want to add incremental ID number in a new column based on current and previous row of another column.我有一个数据框 df,我想根据另一列的当前行和前一行在新列中添加增量 ID 号。
data = [{'X': 6, 'Y': 1}, {'X': 6, 'Y': 1}, {'X': 7, 'Y': 0}, {'X': 7, 'Y': 0},
{'X': 6, 'Y': 1}, {'X': 7, 'Y': 1}, {'X': 7, 'Y': 0}, {'X': 7, 'Y': 1} ]
df = pd.DataFrame(data)
Now this is the condition,现在条件是这样
if Current X = Previous X & Current Y <> Previous Y,如果当前 X = 前一个 X & 当前 Y <> 前一个 Y,
Then ID_Number = New Incremented Number然后 ID_Number = 新增加的数字
OR或者
if Current X <> Previous X & Current Y = Previous Y,如果当前 X <> 前一个 X & 当前 Y = 前一个 Y,
Then ID_Number = New Incremented Number然后 ID_Number = 新增加的数字
OR或者
if Current X = Previous X & Current Y = Previous Y,如果当前 X = 前一个 X & 当前 Y = 前一个 Y,
Then ID_Number = Same as Previous ID_Number然后 ID_Number = 与之前的 ID_Number 相同
OR或者
if Current X <> Previous X & Current Y <> Previous Y,如果当前 X <> 前一个 X & 当前 Y <> 前一个 Y,
Then ID_Number = New Incremented Number然后 ID_Number = 新增加的数字
Input Dataframe will be look like this输入数据框将如下所示
enter image description here在此处输入图片说明
My expectation Output is this我的期望输出是这个
Look a this snippet, don't forget to handle the first item.看看这个片段,不要忘记处理第一项。 copy paste from ipython.
从 ipython 复制粘贴。
In [10]: id_ =1
In [11]: for first, second in zip(data, data[1:]):
...: if first != second:
...: id_ += 1
...: print(f'{id_} {second}')
...:
...:
see itertools module for more.更多信息请参见 itertools 模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.