Writing a pandas DataFrame to CSV file
To delimit by a tab you can use the sep
argument of to_csv
:
df.to_csv(file_name, sep='\t')
To use a specific encoding (e.g. 'utf-8') use the encoding
argument:
df.to_csv(file_name, sep='\t', encoding='utf-8')
Exporting Pandas Dataframe as CSV
try this in your view function
import csv
import pandas as pd
def get(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="{filename}.csv"'.format(filename='myname')
writer = csv.writer(response)
df = pd.DataFrame([{"name": "haha", "age": 18}, {"name": "haha", "age": 18}])
writer.writerow([column for column in df.columns])
writer.writerows(df.values.tolist())
return response
Value error while writing from one csv file to another using pandas
You need to remove the for loop as follows:
import pandas as pd
import os
for filename in os.listdir("csv files copy"):
filenames = os.path.join("csv files copy", filename)
print(filename)
df = pd.read_csv(filenames, error_bad_lines=False)
df.columns = ["id", "FirstName", "LastName", "UserName", "Phone", "IsContact", "RestrictionReason", "Status", "IsScam", "Date"]
df = df.drop(labels="Status", axis=1)
df = df.reindex(columns=["id", "Phone", "FirstName", "LastName", "UserName","IsContact","IsScam","Date","RestrictionReason"])
df.to_csv(filenames, index=False)
This was causing the error and is not needed. The first time through the loop it correctly removes Status
column and saves the CSV file. The second time through the loop (on the same dataframe) it attempts to do df.columns
again but now there is no Status
column, so an incorrect number of columns are given.
The code for row in df:
would actually iterate over the column names in the dataframe,
e.g. id
then FirstName
etc.
How to write a pandas.DataFrame to csv file with custom header?
You can first create a csv file with the custom text in the first line, and then append the dataframe to it.
with open('file.csv', 'a') as file:
file.write('Custom String\n')
df.to_csv(file, header=False, index=False)
Also, see this post.
So, in your case, just use this
with open('file.csv', 'a') as file:
file.write('numrows numcols note\n')
df.to_csv(file, header=False, index=False)
Write pandas DataFrame to CSV file. The result gets extra rows
First try to export as Excel format:
gpa_full.to_excel("gpa_full.xlsx", encoding='utf-8')
If you want a csv file, try to change the separator sep
:
gpa_full.to_csv("gpa_full.csv", sep='\t', encoding='utf-8')
Related Topics
Instance Variables VS. Class Variables in Python
What Do *Args and **Kwargs Mean
Removing Elements That Have Consecutive Duplicates
Python Error "Importerror: No Module Named"
Class Method Differences in Python: Bound, Unbound and Static
Else Clause on Python While Statement
Python: Changes to My Copy Variable Affect the Original Variable
Using Pip to Install Packages to Anaconda Environment
Python Script Not Working via Cron
How to Get the Pythonpath in Shell
Convert Binary to Ascii and Vice Versa
Using Pandas to Pd.Read_Excel() for Multiple Worksheets of the Same Workbook
Why Does Id({}) == Id({}) and Id([]) == Id([]) in Cpython
How to Find the Time Difference Between Two Datetime Objects in Python