【问题标题】:Mapping data from Excel sheet1 to sheet2 creates duplicate column in python将数据从 Excel sheet1 映射到 sheet2 在 python 中创建重复列
【发布时间】:2021-03-27 19:58:55
【问题描述】:

我正在尝试使用 pandas 数据框将值从 Sheet1 映射到 sheet2,在 sheet2 中列出列名,但是当我将数据写入工作表 2 时,它将第一列留空并将数据附加到重复列中。

当我尝试打印 dataframe2 时也会发生这种情况

df1 = pd.read_excel(open(r'C:\Users\Desktop\notepad.xlsx', 'rb'), sheet_name='sheet1')
df2 = pd.read_excel(open(r'C:\Users\Desktop\notepad.xlsx', 'rb'), sheet_name='sheet2')


df2['col1'] = df1['col3']
df2['col2'] = df1['col5']
df2['col3'] = df1['col8']
df2['col4'] = df1['col6']

当尝试打印 df1 时,它会给出正确的数据 但是当尝试打印时,df2 列与第一列重复,有空值

print(df2)

Output

col1 col2 col3 col4  col1 col2 col3 col4
NaN  NaN  NaN  NaN   Ind  Aus  Nz   Aus
NaN  NaN  NaN  NaN   Sri  Afg  Chi  Ber
NaN  NaN  NaN  NaN   Usa  Uk   Un   Ind

如何避免具有 Null 值的重复列

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    为避免列名中包含任何非标准字符或列名出现任何其他奇怪问题的潜在问题,您是否尝试过:

    df2[0] = df1['col3']
    df2[1] = df1['col5']
    df2[2] = df1['col8']
    df2[3] = df1['col6']
    

    另外,请问 print(df1) 的输出是什么?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多