【问题标题】:Two columns linked together when renaming in Pandas dataframe在 Pandas 数据框中重命名时将两列链接在一​​起
【发布时间】:2019-11-03 16:05:17
【问题描述】:

我遇到了一个问题,我的数据框的两列似乎链接在一起。我需要通过索引(在下面的代码中)指定要重命名为“Project”的第二列,因为它没有列标题,但是对于某些文件,它似乎会导致没有标题的下一列也被重命名为“Project” .当我尝试在结果数据集中按索引删除该列时,数据集中的两列都被删除。

df = df.rename(columns={df.columns[2]: "项目"}

它似乎对我拥有的某些数据文件执行此操作,但对其他数据文件没有执行此操作,因此不清楚问题出在哪里,或者是否是由于我下面的代码造成的。

数据集将如下所示:

分类 |类别 |项目.... | MTD 预算 |项目

dfs=[]

for i in range(12):
    print (i)
    df = pd.read_excel(files[i],sheet_name = sheet,header = None, usecols=range(1,16))

for row in range(df.shape[0]): 

    for col in range(df.shape[1]):

        if df.iat[row,col] == 'Classification':
            row_start = row
            break
df = df.loc[row_start:]

new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header

df['Region'] = sheet
df['File'] = files[i].rsplit('/',1)[1]
df['Period'] = files[i].rsplit('Overview - ',1)[1][:-5]


df = df.dropna(axis='columns',how='all')
df = df.dropna(axis='index',how='all')

df = df.rename(columns={df.columns[2]: "Project"})
df = df.loc[:, df.columns.notnull()]

df['Classification'] = df['Classification'].fillna(method='ffill')
df['Category'] = df['Category'].fillna(method='ffill')

dfs.append(df)

【问题讨论】:

  • 请给我们一个示例文件进行测试。谢谢。
  • 你能创建一个minimal reproducible example 吗?
  • IIUC: df.loc[:, ~df.columns.duplicated()]

标签: python pandas rename


【解决方案1】:

IIUC,这个 hack 可以:

col_to_change = 2
df.columns = (list(df.columns[:col_to_change]) +
              ['Project'] + 
              list(df.columns[col_to_change+1:]
             )

或者:

df.columns = [col if i!=col_to_change else 'Project' 
                  for i,col in enumerate(df.columns.to_list()) ]

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 2014-10-26
    • 2021-09-03
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2019-09-26
    • 2019-11-08
    • 2012-08-25
    相关资源
    最近更新 更多