繁体   English   中英

Python Pandas Dataframe:如何同时将 append 索引到多个列表?

[英]Python Pandas Dataframe: How to append more than one index to a list at the same time?

用我认为希望是一个更容易理解的问题重写。

我认为问题是,不能一次将 append 多个项目添加到列表中。

想象一下使用 df.iloc[3:6],但它是:myList.append(Start:Finish)

伪代码

# looping through an index and adding something to it when true
for (x)each index in the index:
    if condition is true:
        myList.append(x)

下面的代码有效,但效率低下

# looping through an index and adding something to it when true
for (x)each index in the index:
    if condition is true:
        myList.append(x),myList.append(x+1),myList.append(x+2)

我想做什么

# looping through an index and adding something to it when true
for (x)each index in the index:
    if condition is true:
        myList.append(x -> x+2) #myList.append(x+1),myList.append(x+2)

# so I want: myList.append(x to x+1 to x+2) 
# but without having to keep writing x+this , x+that ...

而不是这个

myList.append(x)、myList.append(x+1)、myList.append(x_2) (等)

我希望能够写出与

myList.append(此 POSITION -> 中间的数字和 -> 最终位置)

如果不够清楚,我很抱歉,我会写意大利面条代码,直到我弄明白

国际大学联盟:

a = []
g = lambda x,y: list(range(x,x+y))
a.append(g(7,4))
a.append(g(11,4))

A:

[[7, 8, 9, 10], [11, 12, 13, 14]]

如果我正确理解您的条件n连续行,其中值正在增加(x1<x2<x3<x4)

此解决方案将有助于:

https://stackoverflow.com/a/65090526/6660373

您需要根据您的要求进行修改。

从该答案中借用代码:

# Is the current "Close" increasing or same (compared with previous row)
df['incr'] = df.Close >= df.Close.shift(fill_value=0)
# Generate the result column
df['DaysDecr'] = df.groupby(df.incr.cumsum()).apply(
    lambda grp: (~grp.incr).cumsum()).reset_index(level=0, drop=True)
df.drop(columns='incr', inplace=True)

N=3
idx = df.loc[(df['DaysDecr'].rolling(window=N , min_periods=N)\
                          .apply(lambda x: (x==0).all()).eq(1))].index
f = lambda x: list(range(x-N+1,x+1))
for i in idx:
    print(f(i)) # <--------- here is your indices where the condition is satisfied

[0, 1, 2]

东风:

    Date        Close       incr    DaysDecr
0   2015-11-27  105.449997  True    0
1   2015-11-30  106.239998  True    0
2   2015-12-01  107.120003  True    0
3   2015-12-02  106.070000  False   1
4   2015-12-03  104.379997  False   2
5   2020-11-18  271.970001  True    0
6   2020-11-19  272.940002  True    0
7   2020-11-20  269.700012  False   1
8   2020-11-23  268.429993  False   2
9   2020-11-24  276.920013  True    0

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM