[英]Python - save x values from a column to list when a number in another column is bigger than the number before
(I'm new to this so I might not know the best way to formulate this question but here goes) (我是新手,所以我可能不知道提出这个问题的最佳方法,但这里是)
I'm using pandas btw!我正在使用pandas顺便说一句!
I am looking for a construct to each time save x values (let's say x=3 so three values) from one column to a list when a number in another column is bigger than the number before.当另一列中的数字大于之前的数字时,我正在寻找一种构造,每次将 x 值(假设 x=3 三个值)从一列保存到列表中。 First number should not be considered.不应考虑第一个数字。 Important to note that there are also missing data in the number column (NaN).需要注意的是,数字列 (NaN) 中也缺少数据。
NumberColumn Value
23 4
23 5
NaN 8
24 6 # <--
24 23 # <--
24 26 # <--
24 11
25 2 # <--
25 1 # <--
25 3 # <--
25 5
Nan 9
26 4 # <--
26 6 # <--
NaN 9 # <--
26 12
Hopefully in the end the new list contains:希望最终新列表包含:
List1 = [6,23,26,2,1,3,4,6,9]
But also they might overlap so:但它们也可能重叠,所以:
NumberColumn Value
27 4
28 5 # <--
NaN 8 # <--
29 6 # <-- <-- overlap!
29 23 # <--
29 26 # <--
Hopefully here the list will contain:希望这里的列表将包含:
List1 = [5, 8, 6, 6, 23, 26]
Thanks for helping me out !谢谢你的协助 !
With the assumption that numbers cannot be smaller than 0:假设数字不能小于 0:
list1 = []
x=3
df.fillna(value=0, inplace=True)
for i in range(1, len(df)):
if df.loc[i, 'NumberColumn']>df.loc[i-1, 'NumberColumn']:
list1 = list1 + df.loc[i:i+x-1, 'Value'].values.tolist()
print(list1)
As a function:作为 function:
def createList(df, x):
list1 = []
df.fillna(value=0, inplace=True)
for i in range(1, len(df)):
if df.loc[i, 'NumberColumn']>df.loc[i-1, 'NumberColumn']:
list1 = list1 + df.loc[i:i+x-1, 'Value'].values.tolist()
return list1
list1 = createList(df, x=3)
print(list1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.