我正在使用一個如下所示的資料框:
A B C D E F G H
ctg.s1.000000F_arrow CDS gene 21215 22825 0 . DAFEIOHN_00017
ctg.s1.000000F_arrow CDS gene 21215 22825 0 . DAFEIOHN_00017
ctg.s1.000000F_arrow CDS gene 64501 66033 0 - . DAFEIOHN_00049
ctg.s1.000000F_arrow CDS gene 70234 78846 0 . DAFEIOHN_00053
ctg.s1.000000F_arrow CDS gene 103455 106526 0 . DAFEIOHN_00074
ctg.s1.000000F_arrow CDS gene 161029 161712 0 . DAFEIOHN_00132
ctg.s1.000000F_arrow CDS gene 170711 171520 0 . DAFEIOHN_00142
ctg.s1.000000F_arrow CDS gene 203959 204450 0 - . DAFEIOHN_00174
ctg.s1.000000F_arrow CDS gene 211381 212196 0 . DAFEIOHN_00184
ctg.s1.000000F_arrow CDS gene 236673 238499 0 . DAFEIOHN_00209
ctg.s1.000000F_arrow CDS gene 533077 533850 0 . DAFEIOHN_00475
ctg.s1.000000F_arrow CDS gene 533995 535194 0 . DAFEIOHN_00572
ctg.s1.000000F_arrow CDS gene 641146 643083 0 . DAFEIOHN_00572
如您所見,H列中有重復的元素,例如DAFEIOHN_00017或DAFEIOHN_00572。我想修改這個資料框以獲得這樣的東西:
A B C D E F G H I
ctg.s1.000000F_arrow CDS gene 21215 22825 0 . DAFEIOHN_00017 2
ctg.s1.000000F_arrow CDS gene 64501 66033 0 - . DAFEIOHN_00049 1
ctg.s1.000000F_arrow CDS gene 70234 78846 0 . DAFEIOHN_00053 1
ctg.s1.000000F_arrow CDS gene 103455 106526 0 . DAFEIOHN_00074 1
ctg.s1.000000F_arrow CDS gene 161029 161712 0 . DAFEIOHN_00132 1
ctg.s1.000000F_arrow CDS gene 170711 171520 0 . DAFEIOHN_00142 1
ctg.s1.000000F_arrow CDS gene 203959 204450 0 - . DAFEIOHN_00174 1
ctg.s1.000000F_arrow CDS gene 211381 212196 0 . DAFEIOHN_00184 1
ctg.s1.000000F_arrow CDS gene 236673 238499 0 . DAFEIOHN_00209 1
ctg.s1.000000F_arrow CDS gene 533077 533850 0 . DAFEIOHN_00475 1
ctg.s1.000000F_arrow CDS gene 533995 535194 0 . DAFEIOHN_00572 2
在第二個資料框中,重復元素僅顯示一次,并且有一個新列I,其中H提供了該列中每個元素的出現次數。
我怎樣才能做到這一點?
謝謝你。
uj5u.com熱心網友回復:
您可以使用drop_duplicates洗掉了在一個特定的列復制行,并使用assign創建與組合回傳值的新列groupby('H'),并transform('count')以確定的每個唯一值的計數H:
df = df.drop_duplicates(subset='H').assign(I=df.groupby('H')['H'].transform('count'))
輸出:
>>> df
A B C D E F G H I
0 ctg.s1.000000F_arrow CDS-gene 21215 22825 0 . DAFEIOHN_00017 2
2 ctg.s1.000000F_arrow CDS-gene 64501 66033 0 - . DAFEIOHN_00049 1
3 ctg.s1.000000F_arrow CDS-gene 70234 78846 0 . DAFEIOHN_00053 1
4 ctg.s1.000000F_arrow CDS-gene 103455 106526 0 . DAFEIOHN_00074 1
5 ctg.s1.000000F_arrow CDS-gene 161029 161712 0 . DAFEIOHN_00132 1
6 ctg.s1.000000F_arrow CDS-gene 170711 171520 0 . DAFEIOHN_00142 1
7 ctg.s1.000000F_arrow CDS-gene 203959 204450 0 - . DAFEIOHN_00174 1
8 ctg.s1.000000F_arrow CDS-gene 211381 212196 0 . DAFEIOHN_00184 1
9 ctg.s1.000000F_arrow CDS-gene 236673 238499 0 . DAFEIOHN_00209 1
10 ctg.s1.000000F_arrow CDS-gene 533077 533850 0 . DAFEIOHN_00475 1
11 ctg.s1.000000F_arrow CDS-gene 533995 535194 0 . DAFEIOHN_00572 2
uj5u.com熱心網友回復:
我們可以groupby像這樣使用 a并計算元素:
df.groupby('H').count()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/392633.html
