我有一些具有相同名稱的列。我想在重復的列名中添加 1
資料
Date Type hi hello stat hi hello
1/1/2022 a 0 0 1 1 0
期望的
Date Type hi hello stat hi1 hello1
1/1/2022 a 0 0 1 1 0
正在做
mask = df['col2'].duplicated(keep=False)
我相信我可以使用掩碼,但不確定如何在不呼叫實際列的情況下有效地實作這一點。我想呼叫完整的資料集并允許演算法更新欺騙。
任何建議表示贊賞
uj5u.com熱心網友回復:
使用內置決議器方法_maybe_dedup_names():
df.columns = pd.io.parsers.base_parser.ParserBase({'usecols': None})._maybe_dedup_names(df.columns)
# Date Type hi hello stat hi.1 hello.1
# 0 1/1/2022 a 0 0 1 1 0
這是 pandas 用來從read_csv().
請注意,它可以擴展到任意數量的重復名稱:
cols = ['hi'] * 3 ['hello'] * 5
pd.io.parsers.base_parser.ParserBase({'usecols': None})._maybe_dedup_names(cols)
# ['hi', 'hi.1', 'hi.2', 'hello', 'hello.1', 'hello.2', 'hello.3', 'hello.4']
在熊貓 < 1.3 中:
df.columns = pd.io.parsers.ParserBase({})._maybe_dedup_names(df.columns)
uj5u.com熱心網友回復:
您需要將重復的操作應用于列名。然后將重復資訊映射到一個字串,然后您可以將其添加到原始列名中。
df.columns = df.columns [{False:'',True:'1'}[x] for x in df.columns.duplicated()]
uj5u.com熱心網友回復:
我們可以做的
s = df.columns.to_series().groupby(df.columns).cumcount().replace({0:''}).astype(str).radd('.')
df.columns = (df.columns s).str.strip('.')
df
Out[153]:
Date Type hi hello stat hi.1 hello.1
0 1/1/2022 a 0 0 1 1 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454631.html
