我在網上搜索不到答案。假設我有一個看起來像這樣的df1,有以下的列名,我不能像大多數在線答案建議的那樣,在所有重復的列名上使用下降。
index year season 1 2 3 年季 1 2 3 年季
0 1991 冬季 7.1 8.3 9。 0 1991 春天 0.5 7.2 1.5
1 1992 冬季 4.2 5.1 8. 2 1991 春天 2.9 6.2 8.1
但是,我需要將列名變成這樣,放棄/洗掉 "年 "的后續列名,但保留 "1,2,3 "和 "季節 "的重復列名,這樣最后的新df2看起來是這樣的:
index year season 1 2 3 季節1 2 3
0 1991 冬季 7.1 8。 3 9.0 春季 0.5 7.2 1.5
1 1992 冬季 4.2 5. 1 8.2 春季 2.9 6.2 8.1
謝謝你,
uj5u.com熱心網友回復:
在你的情況下做
df.loc[:,(df.groupby(level=0, axis=1).cumcount().eq(0) | (df.columns!='year')]
Out[188]。
索引年份 季節 1 2 3季節 1 2 3
0 0 1991 冬季 7.1 8。 3 9.0 春季 0.5 7.2 1.5
1 1 1992 冬季 4.2 5. 1 8.2 春季 2.9 6.2 8.1
uj5u.com熱心網友回復:
使用columns.get_loc,對于重復的標簽將回傳一個布爾陣列,再加上np.where來獲得所有重復的'year'實體的陣列位置,然后我們可以創建一個陣列位置的串列來保留并以這種方式對DataFrame進行切片。
import numpy as np
to_drop = np.where(df.columns.get_loc('year))[0] [1:]
m = [x for x in np.arange(df. shape[1]) if x not in to_drop]
#[0, 1, 2, 3, 4, 5, 7, 8, 9, 10]
df.iloc[:, m]
指數年份 季節 1 2 3 季節 1 2 3
0 0 1991 冬季 7.1 8。 3 9.0 春季 0.5 7.2 1.5
1 1 1992 冬季 4.2 5. 1 8.2 春季 2.9 6.2 8.1
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323990.html
標籤:
上一篇:我如何匯入MagickImage
