简体   繁体   English

在 Pandas 中的 a.csv 文件中删除 DataFrame 的索引列

[英]Dropping the index column from DataFrame in a .csv file in Pandas

I have a python script here:我这里有一个 python 脚本:

import pyodbc
import pandas as pd
from sqlalchemy import create_engine 
import csv

df = pd.read_sql("""script_generator""", conn)

for count, row in df.iterrows():
    row.to_csv('generatedfile{}.sql'.format(count), index=False, index_label=False, quoting=csv.QUOTE_NONE, escapechar=' ')

and when I run it, it creates separate csv files that are formatted in sql. The output looks like this in generatedfile2:当我运行它时,它会创建单独的 csv 文件,这些文件的格式为 sql。output 在 generatedfile2 中看起来像这样:

2
IF    EXISTS  (SELECT  *  FROM  sys.objects  WHERE  object_id  =  OBJECT_ID(N'table1')  AND  type  in  (N'U')) 
 
BEGIN 
 
        PRINT  'DROPPING  TABLE  [dbo].[table1]....' 
 
        DROP  TABLE  [dbo].[table1];   
 
END;   

The rest of the files have this same format.文件的 rest 具有相同的格式。 Is there any way I can change my code to get rid of the "2" at the beginning of the code?有什么办法可以更改我的代码以摆脱代码开头的“2”吗? It won't run properly in SQL because of it.因此它无法在 SQL 中正常运行。 For some reason index_label=False won't get rid of it.出于某种原因 index_label=False 不会摆脱它。 Thanks a bunch!非常感谢!

When running DataFrame.iterrows , row renders as a Pandas Series and not a Data Frame.运行DataFrame.iterrows时, row呈现为 Pandas 系列而不是数据框。 So actually, you are running Series.to_csv .所以实际上,您正在运行Series.to_csv

for count, row in df.iterrows():
    print(type(row))

# <class 'pandas.core.series.Series'>
# <class 'pandas.core.series.Series'>
# <class 'pandas.core.series.Series'>
...

However, this method is not useful to iterate off a single column.但是,此方法不适用于迭代单个列。 Instead, consider simply looping directly on the values of the column (assumed to be entirely your SQL statement).相反,考虑直接在列的值上循环(假设完全是您的 SQL 语句)。 With each iteration, create the corresponding csv file with typical open + write methods.在每次迭代中,使用典型的open + write方法创建相应的 csv 文件。 Use enumerate for sequential numbering for file suffixes.使用enumerate对文件后缀进行顺序编号。

for count, val in enumerate(df['sql_string_column']):
    with open('generatedfile{}.sql'.format(count), 'w') as f:
        f.write(val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM