![](/img/trans.png)
[英]python regular expression "12x4x67" match only the second group of numbers
[英]how to group by the ordered numbers 1, 123, 12, 12.. etc in python
我有一個包含 3303 行的數據。 我在 python 中使用 pandas
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],'B': ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'], 'C': np.random.randn(8),'D': np.random.randn(8), 'E':['1','1','2','3','1','2','1','2',]})
OUTPUT:
A B C D E
0 foo one -1.607303 1.343192 1
1 bar one 2.064340 1.000130 1
2 foo two -0.362983 1.113389 2
3 bar three 0.486864 -0.804323 3
4 foo two 0.111030 -0.322696 1
5 bar two -0.729870 0.912012 2
6 foo one 1.111405 0.076317 1
7 foo three 0.378172 0.298974 2
你知道如何根據數字順序對“E”列進行分組嗎? 意義; 關於如何按第 1 組中的 1,2,3,第 2 組中的 1,2,第 3 組中的 1,第 4 組中的 1,2 等迭代進行分組的任何想法......等等,這樣它就像
A B C D E G
0 foo one -1.607303 1.343192 1 a
1 bar one 2.064340 1.000130 1 b
2 foo two -0.362983 1.113389 2 b
3 bar three 0.486864 -0.804323 3 b
4 foo two 0.111030 -0.322696 1 c
5 bar two -0.729870 0.912012 2 c
6 foo one 1.111405 0.076317 1 d
7 foo three 0.378172 0.298974 2 d
這樣就像新列“H”、“I”具有按“G”分組的“C”和“D”值的總和。 請在這部分建議和指導我
試試這個:
df['G'] = df.E.eq('1').cumsum()
如果每個新組都以“1”開頭,則此方法有效。 如果不是,您需要求助於yatu 的解決方案。
回答你的整個問題:
df[['H','I']] = df.groupby(df.E.eq('1').cumsum())[['C','D']].transform(sum)
可能對這些結果組進行編號是一個更好的主意。 在這種情況下,您可以檢查系列中的值是否小於或等於移位版本,並取cumsum
結果的累積和:
df['G'] = df.E.le(df.E.shift()).cumsum()
print(df)
A B C D E G
0 foo one -1.495356 3.699348 1 0
1 bar one -1.852039 0.569688 1 1
2 foo two 0.875101 0.736014 2 1
3 bar three -0.690525 0.132817 3 1
4 foo two -0.742679 0.138903 1 2
5 bar two -0.435063 1.525082 2 2
6 foo one -0.985005 1.013949 1 3
7 foo three 0.934254 1.157935 2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.