【问题标题】:How to copy two columns from one Excel file to a new one with Pandas如何使用 Pandas 将一个 Excel 文件中的两列复制到一个新文件中
【发布时间】:2022-01-12 15:39:16
【问题描述】:

我需要将 2 列从 Excel 文件“Input.xlsx”复制到新的 Excel 文件“Output.xlsx”。我使用 Pandas 尝试了以下代码,但在“Output.xlsx”文件中,数据全部写入第一行,我不再有 2 列数据。你能帮我修复代码吗? 代码如下:

    import pandas as pd
document1 = pd.ExcelFile('C:\\Users\\PycharmProjects\\Input.xlsx')
sheets=document1.sheet_names
appended_data=[]
df1=pd.read_excel(document1, sheets, usecols=[' Speed of sound (c) [m/s]',' Outlet Temperature (T out) [°C]'])
appended_data.append(df1)
appended_data=pd.DataFrame(appended_data)
appended_data.to_excel('Output.xlsx', index=False)

【问题讨论】:

  • 注意,你不需要在read_excel中使用sheets=document1.sheet_names,然后sheets。只需使用sheet_name=None
  • 注意,非常感谢!

标签: python excel pandas


【解决方案1】:

对于单个文件:

import pandas as pd

fn = 'C:\\Users\\PycharmProjects\\Input.xlsx'

df = pd.read_excel(fn, usecols=[' Speed of sound (c) [m/s]',' Outlet Temperature (T out) [°C]'])
df.to_excel('Output.xlsx', index=False)

对于多个文件:

import pandas as pd

fns = ['Input1.xlsx', 'Input2.xlsx']
column_names = [' Speed of sound (c) [m/s]',' Outlet Temperature (T out) [°C]']

input_dfs = []
for fn in fns:
    input_df = pd.read_excel(fn, usecols=column_names)
    input_dfs.append(input_df)
output_df = pd.concat(input_dfs)
output_df.to_excel('Output.xlsx', index=False)

【讨论】:

  • df1 实际上可能是 DataFrames 的字典。
  • 非常感谢,您的代码运行良好!现在我需要在多个输入 excel 文件(Input1.xlsx、Input2.xlsx ecc)上迭代这段代码,并将每个文件中的两列复制到同一个 Excel 文件 Output.xlsx 中(在同一张表或不同的表中,它不会没关系)..你有什么建议吗?
  • 您可以遍历文件,为每个文件创建一个数据框,最后将它们连接成一个数据框。我已经更新了上面的解决方案。
  • 这行得通,非常感谢!但是,我需要将从不同文件复制的列放在一个并排,而不是像 concat 那样放在另一个之下...我尝试使用 df.merge(),但它不起作用。我还能尝试什么?
猜你喜欢
  • 2021-03-16
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2019-06-27
相关资源
最近更新 更多