使用python和panda将Excel数据表转换为文本文件



我在一个工作项目中很难充分利用panda。简而言之,我必须从excel中获取所有数据,并以另一种设备可以正确读取的方式对其进行格式化。我已经将我需要的所有列推入数据缓冲区,但是我需要检查其中一个数据缓冲区并打印不同的命令(IE在该列中显示健康:我需要在输出文件中首先打印HEAL,如果它说不健康,我需要打印UN,但是如果它说其他任何东西,我需要从数据中删除行,也健康/不健康不会只存在,他们可能有其他的话,但我正在寻找的关键部分是如果包含这些部分。)我将附上示例excel/输出文本,我正在看。

到目前为止,在我的代码中,我已经隔离了我想要的列,并跳过了excel文件将具有的额外空白行,并且我还以分号和新行字符结束。

import pandas as pd 
import numpy as np


#file_name = input("Please input a file to read. It should have a name like File.xlsmn")
file_name = "file.xlsm"
# maybe add a part where if it fails you ask the user again 


read_file = pd.read_excel(file_name, sheet_name = 0, header = 0, index_col = 0, usecols = [" Name", "Comment", "Price", "category", "data to change"], skiprows = 15) # sheet is equal to 0 by default os it will do the first one 

#print("n")
#print(read_file)


# search fe 
#Fruit Name | Comment | Price | Category | Aisle# / data  


#for index, row in read_file.iterrows():  trying to find if healthy or unhealthy or to remove row
#    if cell = Dgiit

#read_file["Fruit Name"] = read_file["Fruit Name"].str.lower() #broken. tring to get name in to paranthees and all lower case. APPLE -> "apple" 
#drop_val = #!digital / supply    
#read_file = read_file[~read_file['A'].isin(drop_val)] ! ( unhealty * | *Healthy )

# saving to a text file 
read_file.to_csv('input2.txt', sep = 't', line_terminator = ';n') # saves data frame to tab seperated text file. need to find out how to have semi colons at the end. 

Excel表格示例

在我检查项目是否属于两个想要的类别(除了想要的类别之外的所有内容都需要删除)之后,我需要将第一列作为命令。

下面是最终输出 的示例
HEALTHY "bannana" "Aisle#-storename" ; // the comment I need from the comment box //(the number comes from data that needs to be manipulated tab, it has some exess info and things i need to conver)
HEALTHY "orange" "Aisle#-storename"; // what came first the color or the fruit. is the fruit named after the color or the color after the fruit
UNHEALTHY "cupcake" "Aisle#-storename"; // not good for you but maybe for the sould 
UNHEALTHY "pizza" "Aisle#-storename";

Here is what I am getting 
Name      Comment   Price   Category    Data;
BANANNA    x           x         x        x ;
APPLE       x          x          x          x;
ORANGE       x          x          x        x       ;

文本文件中的不太对齐,我希望它更结构化。它必须是一个文本文件,因为机器读取文本

我最大的问题是我如何阅读右边的第2到最后一个类别检查是否要删除行并在文本文件的最左边的空间上打印一些命令。

(我还需要对我关心的项目的第二次传递执行price,我必须生成文件的单独部分。)

对于需要更改的数据,我必须在一些IE SHELF323后读取第一个数字前3需要放在我知道的表中并转换为物理地址,23就像架子的行数。这些需要以某种格式打印到最终的TXT文件。

如果我能澄清什么的话。我的python技能不是很好,但我正在努力把它完成。

这样做的目的是自动读取excel文件,并将其转换为可由特定机器读取的txt文件。

试试这段代码,看看它是否有效。下面的代码将把您的每个Excel选项卡转换为带有分隔符的文本文件。

import pandas as pd

sheets_dict = pd.read_excel(r'C:my_file.xlsx', sheet_name=None)
ExcelSheet = pd.DataFrame()
for name, sheet in sheets_dict.items():   
sheet.to_csv (name+'.txt', '|', index = None, header=True)

最新更新