所以这是我的情况。使用 Python 我想从 excel spreadsheet
复制特定列进入特定列进入 csv
工作表。
预填充的列标题名称在每个电子表格中的名称不同,我需要使用子列表作为参数。
例如,在第一个子列表中,excel中的数据列需要从/复制到:
spreadsheet csv
"scan_date" => "date_of_scan"
两个子列表作为参数:从 excel 复制的名称之一,粘贴到 csv 的位置的名称之一。
不确定字典子列表是否比两个单独的子列表更好?
此外,
csv
列标题名称位于 B 行(不是像 Excel 那样的 A 行),其中包含复杂的内容,例如数据框。所以,理想情况下,我希望将子列表转换为数组,
"scan_date"
"date_of_scan"
在 csv 我试过
pandas
和 openpyxl
并且似乎无法弄清楚如何做到这一点的方法/语法。任何帮助将不胜感激。
谢谢你。
澄清编辑:
csv 文件中有一些预先存在的数据。此外,我无法将标题更改为不同的列。因此,如果“date_of_scan”在“RF”列中,那么它必须保留在“RF”列中。例如,我能够将 5 列数据从 excel 复制到临时电子表格中,然后连接到 csv 中,但它总是将粘贴的列移动到 csv 文档的开头(列 A、B、C、D、E )。
最佳答案
如果没有看到您的特定数据集,很难知道答案,但在我看来,更简单的方法可能是简单地将您的 Excel 工作表设为 df
。 , 删除 csv
中除您想要的列之外的所有内容然后写一个csv
与 Pandas 。这是一些伪代码。
import pandas as pd
df=pd.read_excel('your_file_name.xlsx')
drop_cols=[,,,] #list of columns to get rid of
df.drop(drop_cols,axis='columns')
col_dict={'a':'x','b':'y','c':'z'} #however you want to map you new columns in this example abc are old columns and xyz are new ones
#this line will actually rename your columns with the dictionary
df=df.rename(columns=col_dict)
df.to_csv('new_file_name.csv') #write new file
这实际上将在python中运行,但我从虚拟数据而不是excel文件创建了df。
#with dummy data
df=pd.DataFrame([0,1,2],index=['a','b','c']).T
col_dict={'a':'x','b':'y','c':'z'}
df=df.rename(columns=col_dict)
df.to_csv('new_file_name.csv') #write new file
关于Python excel到csv复制具有不同标题名称的列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563211/