'How do I increment value based on value in column and everytime I increment return the value to another column. Pandas
I am currently doing a data analysis internship at a small company and I have to clean up some data using python and pandas. One of the requests was to add a column that has device #1 in correlating with Site #... So when Site # is 0 device #1 is in the following column and when Site # is 1 device #2 is in the following column. The kicker is the device number increases throughout the 350,000 rows and I need to increment the device # up everytime I come across the next set of device numbers. Before the next set of device #'s so in this case 3,4 which is after 1,2 there is a cell with '======' that I use as an indicator to increment up to 3,4 and so on. However I can never get my code to properly increment up to the next set of device #'s when it comes across the indicator.
def z(x):
b=1
if df['Site'] != '======':
x == 0: return b
x == 1: return b + 1
if df['Site'] == '======':
b += 2
df['Device #'] = df['Site'].apply(z)
Solution 1:[1]
This is how this is done:
b=0
def increment(i):
global b
if i == 0:
return i
elif i == "=====":
b += 2
i += b
elif i ==1:
i += 1
return i
df["Device #"] = df["Site"].map(increment)
Or if you insist on using apply, you can do it this way:
df["Device #"] = df["Site"].apply(increment, axis = 1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
