[英]Create a new pandas dataframe from a python list of lists with a column with lists
[英]Assemble and analyze a list of lists from dataframe in python
我有一個看起來有點像這樣的.csv 文件:
COL_A COL_B COL_C
1 2020-05-26T00:01:01 99999
2 2020-05-26T00:01:02 99999
3 2020-05-26T00:01:03 99999
4 2020-05-26T00:01:04 2.3
5 2020-05-26T00:01:05 2.3
6 2020-05-26T00:01:06 2.3
7 2020-05-26T00:01:07 99999
8 2020-05-26T00:01:08 99999
9 2020-05-26T00:01:09 3.4
10 2020-05-26T00:01:10 3.4
11 2020-05-26T00:01:11 99999
12 2020-05-26T00:01:12 99999
我希望能夠識別COL_C
< 5
的最長連續行跨度並返回該行列表。 所需的 output 將類似於:
[
[4 2020-05-26T00:01:04 2.3,
5 2020-05-26T00:01:05 2.3,
6 2020-05-26T00:01:06 2.3]
], 3
我在理論上處理這個問題的方法是建立一個符合標准的列表列表,然后在列表中使用max
,並以len
為鍵。 我試過這個:
import pandas as pd
def max_c(csv_file):
row_list = []
df = pd.read_csv(csv_file)
for i, row in df.iterrows():
while row[2] < 5:
span = [*row]
row_list.append(span)
return max(row_list, key=len)
我知道這對於我正在嘗試做的事情來說不是正確的語法,我什至可以解釋原因,但對獲得所需的 output 知之甚少。
和 Quang 類似,找到大於 5 並創建子組,然后我們只是過濾掉他的值大於 5,並得到transform
count
的組。 選擇max
計數index
s=df.COL_C.ge(5)
s=df.loc[~s,'COL_A'].groupby(s.cumsum()).transform('count')
target=df.loc[s[s==s.max()].index]
Out[299]:
COL_A COL_B COL_C
3 4 2020-05-26T00:01:04 2.3
4 5 2020-05-26T00:01:05 2.3
5 6 2020-05-26T00:01:06 2.3
我將使用cumsum()
來識別塊並進行分組:
s = df['COL_C'].lt(5)
sizes = s.groupby([s,(~s).cumsum()]).transform('size') * s
# max block 1 size
# max_size == 0 means all values are >= 5
max_size = sizes.max()
df[sizes==max_size]
Output:
COL_A COL_B COL_C
3 4 2020-05-26T00:01:04 2.3
4 5 2020-05-26T00:01:05 2.3
5 6 2020-05-26T00:01:06 2.3
細節:
s
是:
0 False
1 False
2 False
3 True
4 True
5 True
6 False
7 False
8 True
9 True
10 False
11 False
Name: COL_C, dtype: bool
如果我們只做s.cumsum()
那么True
顯然屬於不同的組。 相反,我們做(~s).cumsum()
我們得到:
0 1
1 2
2 3
3 3
4 3
5 3
6 4
7 5
8 5
9 5
10 6
11 7
Name: COL_C, dtype: int64
快到了,但現在每組True
前面都有一行False
。 這表明我們同時按s
和否定的 cumsum 分組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.