无法更改熊猫数据框中单元格的值

时间:2021-02-03 04:19:05

标签: python pandas dataframe

我读取了 excel 文件的工作表 (sh1,sh2,sh3) 并将它们附加到数据框中。 每张表有一行带有列标题的数据:

A   B   C   D   E
20  6   16  6   52

输出数据帧为:

   Unnamed: 0   A   B   C   D   E 
 0  0          20   6   16  6   52
 1  0          4    18  22  18  54
 2  0          2    18  39  18  58
 3  0          4    18  10  18  38
 4  0          1    6   18  6   38

在阅读工作表时,我想将“未命名:0”列中的值更改为工作表名称(sh1、sh2、sh3 等),以便输出如下所示:

  Unnamed: 0    A   B   C   D   E 
 0  sh1        20   6   16  6   52
 1  sh2        4    18  22  18  54
 2  sh3        2    18  39  18  58
 3  sh4        4    18  10  18  38
 4  sh5        1    6   18  6   38

我使用了这段代码:

xl=pd.ExcelFile(myfile, None)  # read excel

 for sheet in xl.sheet_names:
        i=xl.sheet_names.index(sheet)  # i will be the index of current row
        df1=pd.read_excel(myfile, sheet_name=f'{sheet}')
        new_df = new_df.append(df1,ignore_index=True)
        new_df.loc[new_df.iloc[i], 'Unnamed: 0']=f'{sheet}'  #this should do the work but it does not 

但 'Unnamed:0' 的值保持不变。我试图更改其他列,但它不起作用。我也试过这些代码而不是上面的最后一行:

选项 1:

new_df._set_value(new_df.iloc[i], 'Unnamed: 0',f'{sheet}')

选项 2:

new_df.at[new_df.iloc[i], 'Unnamed: 0']=f'{sheet}'

选项 3:

new_df.iloc[i]['Unnamed: 0']=f'{sheet}'

谢谢

0 个答案:

没有答案