[英]Dataframe add element from a column based on values contiguity from another columns
I have a df like this:我有一个这样的df:
a=[1,2,10,11,15,16,17,18,30]
b=[5,6,7,8,9,1,2,3,4]
df=pd.DataFrame(list(zip(a,b)),columns=['s','i'])
Using a I need to add elements of b.使用 a 我需要添加 b 的元素。
Result I would like:结果我想要:
(1-2)=5+6=11 (1-2)=5+6=11
(10-11)=7+8=15 (10-11)=7+8=15
(15-18)=9+1+2+3=15 (15-18)=9+1+2+3=15
(30)=4 (30)=4
My idea was to create a list of values that are continuous, take the difference(+1) and use it to calculate the sum of the corresponding b elements.我的想法是创建一个连续值的列表,取差(+1)并用它来计算相应 b 元素的总和。
#find continuous integer
def r (nums):
nums= list(df['s'])
gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e]
edges = iter(nums[:1] + sum(gaps, []) + nums[-1:])
return (list(zip(edges, edges)))
#difference
a = r(df)
print (a)
for i in range (len(a)):
diff = np.diff(a[i])+1
I am trying to use diff as a counter to add the value of b but obviously any single time the addition starts from the first value.我正在尝试使用 diff 作为计数器来添加 b 的值,但显然任何一次添加都从第一个值开始。 There is any simple way to add this number without changing b?
有什么简单的方法可以在不改变 b 的情况下添加这个数字?
Using groupby
+ diff
使用
groupby
+ diff
df['i'].groupby(df['s'].diff().ne(1).cumsum()).sum()
1 11
2 15
3 15
4 4
Name: i, dtype: int64
Another solution:另一种解决方案:
df.groupby( ((df.s-df.s.shift(1))!=1).cumsum() ).i.sum()
reult:结果:
1 11
2 15
3 15
4 4
Name: i, dtype: int64
You could use NumPy
as:您可以使用
NumPy
作为:
res = []
arr = df.values.copy()
for i in range(1, arr.shape[0]):
if arr[i, 0] == arr[i-1, 0] + 1:
arr[i, 1] = arr[i, 1] + arr[i-1, 1]
else:
res.append(arr[i-1, 1])
res.append(arr[-1, 1])
res
This will give:这将给出:
[11, 15, 15, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.