我已经编写了一个使用regex函数清除csv文件并将其导出到csv的函数。该函数的输入fn_file将从文件夹“ x”中获取文件名为file.csv的文件,并处理该文件,并将处理后的文件作为“ file_processed.csv”导出到“ x”文件夹中。将数据帧转换为csv时,显示以下错误。如何将标题作为列添加到文件
Function
--------
process_file
Use regex to create a file with title,date and header
Parameters
----------
fn_file : str
Name of file scraped from WDET
fn_out : str
Name of new, reformatted, file
Returns
-------
Nothing returned. Just creates output file.
Example
-------
process_file('E:/data.csv' , 'E:/data_processed.csv')
提高ValueError('DataFrame构造函数未正确调用!') ValueError:DataFrame构造函数未正确调用!
s_df = pd.DataFrame(数据= fn_file,列= [标题])
我的代码如下
def process_file(fn_file , fn_csv_out):
s = re.compile(r'.*?word.+?\(\d{1,2}[ap]m-\d{1,2}[ap]m\)\s+$')
date = re.compile(r'(Sunday)\s+(\w+\s+\d+,\s+(2010))')
he = re.compile(r'\t\w+.\t\w+\t\w+\t\w+\s\(\w+\)\t\w+$')
son = re.compile(r'^.*\t\d+\t.+\t')
# Initialize counters
num_lines = 0
num_s = 0
num_date = 0
num_he = 0
num_son = 0
num_unmatched = 0
# Initialize empty list to store output lines
sonlines = []
# Initialize string vars to use for the show title and date
title = ''
date = ''
with open(fn_file) as f:
# Loop over the lines in the file
for line in f:
num_lines +=1
line = line.rstrip('\n')
m_s = re.match(s, line)
m_date = re.match(date, line)
m_he = re.match(he, line)
m_son = re.match(son, line)
if m_s:
num_s += 1
# Get the show title
ti = m_s.group()
elif m_date:
# it's a date line
num_date += 1
show_day = m_date.group(1)
s_date = m_date.group(2)
elif m_he:
# it's a header line
num_he += 1
heline = m_he.group()
elif m_son:
num_son += 1
son_group = m_son.group()
son = re.split(r'\t+', son_group)
son.insert(0,ti)
son.insert(1,s_date)
sonlines.append(son)
header = re.split(r'\t+',heline.rstrip('\t'))
header[0] = 'b'
header.insert(0,'ti')
header.insert(1,'s_date')
# Create pandas dataframe and export to csv
```lines throwing error
s_df = pd.DataFrame(data = fn_file, columns = [header])
s_df.to_csv(fn_csv_out, sep='\t', index= False)
Last two lines are throwing error, Can you please help on the error. Thanks in advance.
答案 0 :(得分:0)
问题已通过注释解决。该变量被传递给DataFrame构造函数。修复它,因此将其更改为
s_df = pd.DataFrame(data = sonlines, columns = [header])
代替
s_df = pd.DataFrame(data = fn_file, columns = [header])