Incrementing add under condition in pandasDoes Python have a ternary conditional operator?Add new keys to a dictionary?Converting a Pandas GroupBy output from Series to DataFrameRenaming columns in pandasAdding new column to existing DataFrame in Python pandasHow can I replace all the NaN values with Zero's in a column of a pandas dataframe“Large data” work flows using pandasChange data type of columns in PandasSelect rows from a DataFrame based on values in a column in pandasWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?
Looking for a new job because of relocation - is it okay to tell the real reason?
Can a PC attack themselves with an unarmed strike?
Yajilin minicubes: the Hullabaloo, the Brouhaha, the Bangarang
What are good ways to improve as a writer other than writing courses?
Is this cheap "air conditioner" able to cool a room?
Can an SPI slave start a transmission in full-duplex mode?
Why does Intel's Haswell chip allow multiplication to be twice as fast as addition?
How quickly could a country build a tall concrete wall around a city?
How can glass marbles naturally occur in a desert?
sed delete all the words before a match
Is it true that control+alt+delete only became a thing because IBM would not build Bill Gates a computer with a task manager button?
Geometric programming: Why are the constraints defined to be less than/equal to 1?
Why are physicists so interested in irreps if in their non-block-diagonal form they mix all components of a vector?
How to display a duet in lyrics?
Pandas: fill one column with count of # of obs between occurrences in a 2nd column
Could one become a successful researcher by writing some really good papers while being outside academia?
Best gun to modify into a monsterhunter weapon?
Generator for parity?
What happen if I gain the control of aura that enchants an opponent's creature? Would the aura stay attached?
Does this smartphone photo show Mars just below the Sun?
Can we use other things than single-word verbs in our dialog tags?
Where to pee in London?
Why should public servants be apolitical?
During the Space Shuttle Columbia Disaster of 2003, Why Did The Flight Director Say, "Lock the doors."?
Incrementing add under condition in pandas
Does Python have a ternary conditional operator?Add new keys to a dictionary?Converting a Pandas GroupBy output from Series to DataFrameRenaming columns in pandasAdding new column to existing DataFrame in Python pandasHow can I replace all the NaN values with Zero's in a column of a pandas dataframe“Large data” work flows using pandasChange data type of columns in PandasSelect rows from a DataFrame based on values in a column in pandasWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
For the following pandas dataframe
servo_in_position second_servo_in_position Expected output
0 0 1 0
1 0 1 0
2 1 2 1
3 0 3 0
4 1 4 2
5 1 4 2
6 0 5 0
7 0 5 0
8 1 6 3
9 0 7 0
10 1 8 4
11 0 9 0
12 1 10 5
13 1 10 5
14 1 10 5
15 0 11 0
16 0 11 0
17 0 11 0
18 1 12 6
19 1 12 6
20 0 13 0
21 0 13 0
22 0 13 0
I want to increment the column "Expected output" only if "servo_in_position" changes from 0 to 1. I want also to assume "Expected output" to be 0 (null) if "servo_in_position" equals to 0.
I tried
input_data['second_servo_in_position']=(input_data.servo_in_position.diff()!=0).cumsum()
but it gives output as in "second_servo_in_position" column, which is not what I wanted.
After that I would like to group and calculate mean using:
print("Mean=nn",input_data.groupby('second_servo_in_position').mean())
python pandas
add a comment |
For the following pandas dataframe
servo_in_position second_servo_in_position Expected output
0 0 1 0
1 0 1 0
2 1 2 1
3 0 3 0
4 1 4 2
5 1 4 2
6 0 5 0
7 0 5 0
8 1 6 3
9 0 7 0
10 1 8 4
11 0 9 0
12 1 10 5
13 1 10 5
14 1 10 5
15 0 11 0
16 0 11 0
17 0 11 0
18 1 12 6
19 1 12 6
20 0 13 0
21 0 13 0
22 0 13 0
I want to increment the column "Expected output" only if "servo_in_position" changes from 0 to 1. I want also to assume "Expected output" to be 0 (null) if "servo_in_position" equals to 0.
I tried
input_data['second_servo_in_position']=(input_data.servo_in_position.diff()!=0).cumsum()
but it gives output as in "second_servo_in_position" column, which is not what I wanted.
After that I would like to group and calculate mean using:
print("Mean=nn",input_data.groupby('second_servo_in_position').mean())
python pandas
add a comment |
For the following pandas dataframe
servo_in_position second_servo_in_position Expected output
0 0 1 0
1 0 1 0
2 1 2 1
3 0 3 0
4 1 4 2
5 1 4 2
6 0 5 0
7 0 5 0
8 1 6 3
9 0 7 0
10 1 8 4
11 0 9 0
12 1 10 5
13 1 10 5
14 1 10 5
15 0 11 0
16 0 11 0
17 0 11 0
18 1 12 6
19 1 12 6
20 0 13 0
21 0 13 0
22 0 13 0
I want to increment the column "Expected output" only if "servo_in_position" changes from 0 to 1. I want also to assume "Expected output" to be 0 (null) if "servo_in_position" equals to 0.
I tried
input_data['second_servo_in_position']=(input_data.servo_in_position.diff()!=0).cumsum()
but it gives output as in "second_servo_in_position" column, which is not what I wanted.
After that I would like to group and calculate mean using:
print("Mean=nn",input_data.groupby('second_servo_in_position').mean())
python pandas
For the following pandas dataframe
servo_in_position second_servo_in_position Expected output
0 0 1 0
1 0 1 0
2 1 2 1
3 0 3 0
4 1 4 2
5 1 4 2
6 0 5 0
7 0 5 0
8 1 6 3
9 0 7 0
10 1 8 4
11 0 9 0
12 1 10 5
13 1 10 5
14 1 10 5
15 0 11 0
16 0 11 0
17 0 11 0
18 1 12 6
19 1 12 6
20 0 13 0
21 0 13 0
22 0 13 0
I want to increment the column "Expected output" only if "servo_in_position" changes from 0 to 1. I want also to assume "Expected output" to be 0 (null) if "servo_in_position" equals to 0.
I tried
input_data['second_servo_in_position']=(input_data.servo_in_position.diff()!=0).cumsum()
but it gives output as in "second_servo_in_position" column, which is not what I wanted.
After that I would like to group and calculate mean using:
print("Mean=nn",input_data.groupby('second_servo_in_position').mean())
python pandas
python pandas
edited Jul 29 at 14:35
Scott Boston
65.9k7 gold badges39 silver badges63 bronze badges
65.9k7 gold badges39 silver badges63 bronze badges
asked Jul 29 at 13:31
TomaszTomasz
878 bronze badges
878 bronze badges
add a comment |
add a comment |
5 Answers
5
active
oldest
votes
Use cumsum and mask:
df['E_output'] = df['servo_in_position'].diff().eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
Output:
servo_in_position second_servo_in_position Expected output E_output
0 0 1 0 0
1 0 1 0 0
2 1 2 1 1
3 0 3 0 0
4 1 4 2 2
5 1 4 2 2
6 0 5 0 0
7 0 5 0 0
8 1 6 3 3
9 0 7 0 0
10 1 8 4 4
11 0 9 0 0
12 1 10 5 5
13 1 10 5 5
14 1 10 5 5
15 0 11 0 0
16 0 11 0 0
17 0 11 0 0
18 1 12 6 6
19 1 12 6 6
20 0 13 0 0
21 0 13 0 0
22 0 13 0 0
Update for first position equal to 1.
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row equals to 0, but should be 1.
– Tomasz
Aug 6 at 14:04
@Tomasz Try that updated statement at the bottom. Let me know if that works or not. Thanks.
– Scott Boston
Aug 6 at 14:17
@Tomasaz What I did is was to fill that first NaN caused by the diff for the first value, to fill with the first value in 'servo_in_position' hence, it will return the current state of the first value. I think this should work.
– Scott Boston
Aug 6 at 14:19
1
It worked, thank you! Here is the code:import pandas as pd import numpy as np data = [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1] df = pd.DataFrame(data, columns = ['servo_in_position']) print("Groupping data according to servo positions, please wait...") df['groupped_measurement']=df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0) print("Data groupped successfully!") print("Input data:n",df)
– Tomasz
Aug 6 at 14:29
add a comment |
Using cumsum and arithmetic.
u = df['servo_in_position']
(u.eq(1) & u.shift().ne(1)).cumsum() * u
0 0
1 0
2 1
3 0
4 2
5 2
6 0
7 0
8 3
9 0
10 4
11 0
12 5
13 5
14 5
15 0
16 0
17 0
18 6
19 6
20 0
21 0
22 0
Name: servo_in_position, dtype: int64
add a comment |
Try np.where:
df['Expected_output'] = np.where(df.servo_in_position.eq(1),
df.servo_in_position.diff().eq(1).cumsum(),
0)
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row will equal to 0, but should be 1.
– Tomasz
Aug 6 at 14:06
add a comment |
That is cumsum and mul
df.servo_in_position.diff().eq(1).cumsum().mul(df.servo_in_position.eq(1),axis=0)
add a comment |
Fast with Numba
from numba import njit
@njit
def f(u):
out = np.zeros(len(u), np.int64)
a = out[0] = u[0]
for i in range(1, len(u)):
if u[i] == 1:
if u[i - 1] == 0:
a += 1
out[i] = a
return out
f(df.servo_in_position.to_numpy())
array([0, 0, 1, 0, 2, 2, 0, 0, 3, 0, 4, 0, 5, 5, 5, 0, 0, 0, 6, 6, 0, 0, 0])
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57254964%2fincrementing-add-under-condition-in-pandas%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use cumsum and mask:
df['E_output'] = df['servo_in_position'].diff().eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
Output:
servo_in_position second_servo_in_position Expected output E_output
0 0 1 0 0
1 0 1 0 0
2 1 2 1 1
3 0 3 0 0
4 1 4 2 2
5 1 4 2 2
6 0 5 0 0
7 0 5 0 0
8 1 6 3 3
9 0 7 0 0
10 1 8 4 4
11 0 9 0 0
12 1 10 5 5
13 1 10 5 5
14 1 10 5 5
15 0 11 0 0
16 0 11 0 0
17 0 11 0 0
18 1 12 6 6
19 1 12 6 6
20 0 13 0 0
21 0 13 0 0
22 0 13 0 0
Update for first position equal to 1.
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row equals to 0, but should be 1.
– Tomasz
Aug 6 at 14:04
@Tomasz Try that updated statement at the bottom. Let me know if that works or not. Thanks.
– Scott Boston
Aug 6 at 14:17
@Tomasaz What I did is was to fill that first NaN caused by the diff for the first value, to fill with the first value in 'servo_in_position' hence, it will return the current state of the first value. I think this should work.
– Scott Boston
Aug 6 at 14:19
1
It worked, thank you! Here is the code:import pandas as pd import numpy as np data = [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1] df = pd.DataFrame(data, columns = ['servo_in_position']) print("Groupping data according to servo positions, please wait...") df['groupped_measurement']=df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0) print("Data groupped successfully!") print("Input data:n",df)
– Tomasz
Aug 6 at 14:29
add a comment |
Use cumsum and mask:
df['E_output'] = df['servo_in_position'].diff().eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
Output:
servo_in_position second_servo_in_position Expected output E_output
0 0 1 0 0
1 0 1 0 0
2 1 2 1 1
3 0 3 0 0
4 1 4 2 2
5 1 4 2 2
6 0 5 0 0
7 0 5 0 0
8 1 6 3 3
9 0 7 0 0
10 1 8 4 4
11 0 9 0 0
12 1 10 5 5
13 1 10 5 5
14 1 10 5 5
15 0 11 0 0
16 0 11 0 0
17 0 11 0 0
18 1 12 6 6
19 1 12 6 6
20 0 13 0 0
21 0 13 0 0
22 0 13 0 0
Update for first position equal to 1.
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row equals to 0, but should be 1.
– Tomasz
Aug 6 at 14:04
@Tomasz Try that updated statement at the bottom. Let me know if that works or not. Thanks.
– Scott Boston
Aug 6 at 14:17
@Tomasaz What I did is was to fill that first NaN caused by the diff for the first value, to fill with the first value in 'servo_in_position' hence, it will return the current state of the first value. I think this should work.
– Scott Boston
Aug 6 at 14:19
1
It worked, thank you! Here is the code:import pandas as pd import numpy as np data = [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1] df = pd.DataFrame(data, columns = ['servo_in_position']) print("Groupping data according to servo positions, please wait...") df['groupped_measurement']=df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0) print("Data groupped successfully!") print("Input data:n",df)
– Tomasz
Aug 6 at 14:29
add a comment |
Use cumsum and mask:
df['E_output'] = df['servo_in_position'].diff().eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
Output:
servo_in_position second_servo_in_position Expected output E_output
0 0 1 0 0
1 0 1 0 0
2 1 2 1 1
3 0 3 0 0
4 1 4 2 2
5 1 4 2 2
6 0 5 0 0
7 0 5 0 0
8 1 6 3 3
9 0 7 0 0
10 1 8 4 4
11 0 9 0 0
12 1 10 5 5
13 1 10 5 5
14 1 10 5 5
15 0 11 0 0
16 0 11 0 0
17 0 11 0 0
18 1 12 6 6
19 1 12 6 6
20 0 13 0 0
21 0 13 0 0
22 0 13 0 0
Update for first position equal to 1.
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
Use cumsum and mask:
df['E_output'] = df['servo_in_position'].diff().eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
Output:
servo_in_position second_servo_in_position Expected output E_output
0 0 1 0 0
1 0 1 0 0
2 1 2 1 1
3 0 3 0 0
4 1 4 2 2
5 1 4 2 2
6 0 5 0 0
7 0 5 0 0
8 1 6 3 3
9 0 7 0 0
10 1 8 4 4
11 0 9 0 0
12 1 10 5 5
13 1 10 5 5
14 1 10 5 5
15 0 11 0 0
16 0 11 0 0
17 0 11 0 0
18 1 12 6 6
19 1 12 6 6
20 0 13 0 0
21 0 13 0 0
22 0 13 0 0
Update for first position equal to 1.
df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum()
.mask(df['servo_in_position'] == 0, 0)
edited Aug 6 at 14:47
answered Jul 29 at 13:36
Scott BostonScott Boston
65.9k7 gold badges39 silver badges63 bronze badges
65.9k7 gold badges39 silver badges63 bronze badges
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row equals to 0, but should be 1.
– Tomasz
Aug 6 at 14:04
@Tomasz Try that updated statement at the bottom. Let me know if that works or not. Thanks.
– Scott Boston
Aug 6 at 14:17
@Tomasaz What I did is was to fill that first NaN caused by the diff for the first value, to fill with the first value in 'servo_in_position' hence, it will return the current state of the first value. I think this should work.
– Scott Boston
Aug 6 at 14:19
1
It worked, thank you! Here is the code:import pandas as pd import numpy as np data = [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1] df = pd.DataFrame(data, columns = ['servo_in_position']) print("Groupping data according to servo positions, please wait...") df['groupped_measurement']=df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0) print("Data groupped successfully!") print("Input data:n",df)
– Tomasz
Aug 6 at 14:29
add a comment |
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row equals to 0, but should be 1.
– Tomasz
Aug 6 at 14:04
@Tomasz Try that updated statement at the bottom. Let me know if that works or not. Thanks.
– Scott Boston
Aug 6 at 14:17
@Tomasaz What I did is was to fill that first NaN caused by the diff for the first value, to fill with the first value in 'servo_in_position' hence, it will return the current state of the first value. I think this should work.
– Scott Boston
Aug 6 at 14:19
1
It worked, thank you! Here is the code:import pandas as pd import numpy as np data = [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1] df = pd.DataFrame(data, columns = ['servo_in_position']) print("Groupping data according to servo positions, please wait...") df['groupped_measurement']=df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0) print("Data groupped successfully!") print("Input data:n",df)
– Tomasz
Aug 6 at 14:29
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row equals to 0, but should be 1.
– Tomasz
Aug 6 at 14:04
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row equals to 0, but should be 1.
– Tomasz
Aug 6 at 14:04
@Tomasz Try that updated statement at the bottom. Let me know if that works or not. Thanks.
– Scott Boston
Aug 6 at 14:17
@Tomasz Try that updated statement at the bottom. Let me know if that works or not. Thanks.
– Scott Boston
Aug 6 at 14:17
@Tomasaz What I did is was to fill that first NaN caused by the diff for the first value, to fill with the first value in 'servo_in_position' hence, it will return the current state of the first value. I think this should work.
– Scott Boston
Aug 6 at 14:19
@Tomasaz What I did is was to fill that first NaN caused by the diff for the first value, to fill with the first value in 'servo_in_position' hence, it will return the current state of the first value. I think this should work.
– Scott Boston
Aug 6 at 14:19
1
1
It worked, thank you! Here is the code:
import pandas as pd import numpy as np data = [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1] df = pd.DataFrame(data, columns = ['servo_in_position']) print("Groupping data according to servo positions, please wait...") df['groupped_measurement']=df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0) print("Data groupped successfully!") print("Input data:n",df)– Tomasz
Aug 6 at 14:29
It worked, thank you! Here is the code:
import pandas as pd import numpy as np data = [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1] df = pd.DataFrame(data, columns = ['servo_in_position']) print("Groupping data according to servo positions, please wait...") df['groupped_measurement']=df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0) print("Data groupped successfully!") print("Input data:n",df)– Tomasz
Aug 6 at 14:29
add a comment |
Using cumsum and arithmetic.
u = df['servo_in_position']
(u.eq(1) & u.shift().ne(1)).cumsum() * u
0 0
1 0
2 1
3 0
4 2
5 2
6 0
7 0
8 3
9 0
10 4
11 0
12 5
13 5
14 5
15 0
16 0
17 0
18 6
19 6
20 0
21 0
22 0
Name: servo_in_position, dtype: int64
add a comment |
Using cumsum and arithmetic.
u = df['servo_in_position']
(u.eq(1) & u.shift().ne(1)).cumsum() * u
0 0
1 0
2 1
3 0
4 2
5 2
6 0
7 0
8 3
9 0
10 4
11 0
12 5
13 5
14 5
15 0
16 0
17 0
18 6
19 6
20 0
21 0
22 0
Name: servo_in_position, dtype: int64
add a comment |
Using cumsum and arithmetic.
u = df['servo_in_position']
(u.eq(1) & u.shift().ne(1)).cumsum() * u
0 0
1 0
2 1
3 0
4 2
5 2
6 0
7 0
8 3
9 0
10 4
11 0
12 5
13 5
14 5
15 0
16 0
17 0
18 6
19 6
20 0
21 0
22 0
Name: servo_in_position, dtype: int64
Using cumsum and arithmetic.
u = df['servo_in_position']
(u.eq(1) & u.shift().ne(1)).cumsum() * u
0 0
1 0
2 1
3 0
4 2
5 2
6 0
7 0
8 3
9 0
10 4
11 0
12 5
13 5
14 5
15 0
16 0
17 0
18 6
19 6
20 0
21 0
22 0
Name: servo_in_position, dtype: int64
answered Jul 29 at 13:36
user3483203user3483203
37.3k8 gold badges31 silver badges60 bronze badges
37.3k8 gold badges31 silver badges60 bronze badges
add a comment |
add a comment |
Try np.where:
df['Expected_output'] = np.where(df.servo_in_position.eq(1),
df.servo_in_position.diff().eq(1).cumsum(),
0)
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row will equal to 0, but should be 1.
– Tomasz
Aug 6 at 14:06
add a comment |
Try np.where:
df['Expected_output'] = np.where(df.servo_in_position.eq(1),
df.servo_in_position.diff().eq(1).cumsum(),
0)
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row will equal to 0, but should be 1.
– Tomasz
Aug 6 at 14:06
add a comment |
Try np.where:
df['Expected_output'] = np.where(df.servo_in_position.eq(1),
df.servo_in_position.diff().eq(1).cumsum(),
0)
Try np.where:
df['Expected_output'] = np.where(df.servo_in_position.eq(1),
df.servo_in_position.diff().eq(1).cumsum(),
0)
answered Jul 29 at 13:33
Quang HoangQuang Hoang
15.6k2 gold badges14 silver badges25 bronze badges
15.6k2 gold badges14 silver badges25 bronze badges
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row will equal to 0, but should be 1.
– Tomasz
Aug 6 at 14:06
add a comment |
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row will equal to 0, but should be 1.
– Tomasz
Aug 6 at 14:06
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row will equal to 0, but should be 1.
– Tomasz
Aug 6 at 14:06
What to do if servo_in_position in 0th row is equal to 1? With your code E_output in 0th row will equal to 0, but should be 1.
– Tomasz
Aug 6 at 14:06
add a comment |
That is cumsum and mul
df.servo_in_position.diff().eq(1).cumsum().mul(df.servo_in_position.eq(1),axis=0)
add a comment |
That is cumsum and mul
df.servo_in_position.diff().eq(1).cumsum().mul(df.servo_in_position.eq(1),axis=0)
add a comment |
That is cumsum and mul
df.servo_in_position.diff().eq(1).cumsum().mul(df.servo_in_position.eq(1),axis=0)
That is cumsum and mul
df.servo_in_position.diff().eq(1).cumsum().mul(df.servo_in_position.eq(1),axis=0)
answered Jul 29 at 13:55
WeNYoBenWeNYoBen
152k8 gold badges53 silver badges84 bronze badges
152k8 gold badges53 silver badges84 bronze badges
add a comment |
add a comment |
Fast with Numba
from numba import njit
@njit
def f(u):
out = np.zeros(len(u), np.int64)
a = out[0] = u[0]
for i in range(1, len(u)):
if u[i] == 1:
if u[i - 1] == 0:
a += 1
out[i] = a
return out
f(df.servo_in_position.to_numpy())
array([0, 0, 1, 0, 2, 2, 0, 0, 3, 0, 4, 0, 5, 5, 5, 0, 0, 0, 6, 6, 0, 0, 0])
add a comment |
Fast with Numba
from numba import njit
@njit
def f(u):
out = np.zeros(len(u), np.int64)
a = out[0] = u[0]
for i in range(1, len(u)):
if u[i] == 1:
if u[i - 1] == 0:
a += 1
out[i] = a
return out
f(df.servo_in_position.to_numpy())
array([0, 0, 1, 0, 2, 2, 0, 0, 3, 0, 4, 0, 5, 5, 5, 0, 0, 0, 6, 6, 0, 0, 0])
add a comment |
Fast with Numba
from numba import njit
@njit
def f(u):
out = np.zeros(len(u), np.int64)
a = out[0] = u[0]
for i in range(1, len(u)):
if u[i] == 1:
if u[i - 1] == 0:
a += 1
out[i] = a
return out
f(df.servo_in_position.to_numpy())
array([0, 0, 1, 0, 2, 2, 0, 0, 3, 0, 4, 0, 5, 5, 5, 0, 0, 0, 6, 6, 0, 0, 0])
Fast with Numba
from numba import njit
@njit
def f(u):
out = np.zeros(len(u), np.int64)
a = out[0] = u[0]
for i in range(1, len(u)):
if u[i] == 1:
if u[i - 1] == 0:
a += 1
out[i] = a
return out
f(df.servo_in_position.to_numpy())
array([0, 0, 1, 0, 2, 2, 0, 0, 3, 0, 4, 0, 5, 5, 5, 0, 0, 0, 6, 6, 0, 0, 0])
answered Jul 29 at 15:21
piRSquaredpiRSquared
175k26 gold badges191 silver badges346 bronze badges
175k26 gold badges191 silver badges346 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57254964%2fincrementing-add-under-condition-in-pandas%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown