简体   繁体   English

如何在 dataframe 中创建新列,当另一列中的 diff() 小于 0 时添加 1?

[英]How to create new column in a dataframe that add 1 when diff() within another column is less than 0?

I have this data:我有这个数据:

data = pd.DataFrame([0.0, 0.1, 0.2, 0.3, 1.5, 2.7, 3.8, 0.0, 0.3, 0.8, 1.2, 2.5, 3.5, 0.0, 0.5, 1.0, 3.0, 0.0, 1.5, 2.6, 3.6, 4.0])

I have more than just one column, but I am providing the column I am interested in.我有不止一个专栏,但我提供了我感兴趣的专栏。

I need to add another column called 'iteration' that should look like this:我需要添加另一个名为“迭代”的列,应该如下所示:

data = pd.DataFrame([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4])

In other words, every single time the difference between row+1 and row is less than zero, the iteration row should increase by one unit.换句话说,每一次 row+1 和 row 之间的差值小于零,迭代行就应该增加一个单位。 For example: 0.0 - 3.8 = -3.8.例如:0.0 - 3.8 = -3.8。 At this point, the iteration should increase by one unit.此时,迭代应该增加一个单位。

Try with diff then cumsum尝试diff然后cumsum

out = (data[0].diff()<0).cumsum()+1
Out[24]: 
0     1
1     1
2     1
3     1
4     1
5     1
6     1
7     2
8     2
9     2
10    2
11    2
12    2
13    3
14    3
15    3
16    3
17    4
18    4
19    4
20    4
21    4
Name: 0, dtype: int32

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在数据框中使用该数据框中另一列的值创建一个新列,但在 1 小时内 - How to create a new column in a dataframe with the value of another column in that dataframe, but within 1 hour 如何在数据帧中创建新列,该列将是另一列的函数,并且条件上比for循环快? - How to create a new column in dataframe, which will be a function of another column and conditionals faster than a for loop? 如何基于另一个DataFrame中的列在Pandas DataFrame中创建新列? - How to create a new column in a Pandas DataFrame based on a column in another DataFrame? 如何通过将另一列乘以常数来在 dataframe 中创建新列? - How to create a new column in a dataframe by multiplying another column by a constant? 如何创建一个新的数据框列,并从另一个列中移出值? - How to create a new dataframe column with shifted values from another column? 检查特定列是否大于另一列并根据 pandas dataframe 中的条件创建新列 - Check if specific column is greater than another column and create a new column based on condition in pandas dataframe 如何根据另一个 dataframe 的匹配为 dataframe 的新列添加值? - how to add value to a new column to a dataframe based on the match of another dataframe? 如何将数据从一个 dataframe 添加到另一个 dataframe 上的新列 - how to add data from one dataframe to a new column on another dataframe 如何通过过滤另一个 dataframe 的列来创建新的 dataframe - How to create new dataframe by filtering a column of another dataframe 如何检查 dataframe 的三列值是否小于另一个标准 dataframe 的同时值? - How to check if three column values of a dataframe are less than simultaneous values of another standard dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM