Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Pandas to_csv()
1
Pandas to_csv()

[Image: graphic-1024x576.jpg]

You can convert a list of lists to aPandas DataFrame that provides you with powerful capabilities such as the
Code:
to_csv()
method
. This is the easiest method and it allows you to avoid importing yet another library (I use Pandas in many Python projects anyways).

Code:
salary = [['Alice', 'Data Scientist', 122000], ['Bob', 'Engineer', 77000], ['Ann', 'Manager', 119000]] # Method 2 import pandas as pd df = pd.DataFrame(salary) df.to_csv('file2.csv', index=False, header=False)

Output:

Code:
# file2.csv Alice,Data Scientist,122000 Bob,Engineer,77000 Ann,Manager,119000

You create a Pandas DataFrame—which is Python’s default representation of tabular data. Think of it as an Excel spreadsheet within your code (with rows and columns).

The DataFrame is a very powerful data structure that allows you to perform various methods. One of those is the
Code:
to_csv()
method that allows you to write its contents into a CSV file.

You set the
Code:
index
and
Code:
header
arguments of the
Code:
to_csv()
method to
Code:
False
because Pandas, per default, adds integer row and column indices 0, 1, 2, …. Again, think of them as the row and column indices in your Excel spreadsheet. You don’t want them to appear in the CSV file so you set the arguments to
Code:
False
.

If you want to customize the CSV output, you’ve got a lot of special arguments to play with. Check out thisarticle for a comprehensive list of all arguments.

Related article:Pandas Cheat Sheets to Pin to Your Wall

Feel free to play with alternative methods to convert a list of lists to a CSV filein our interactive code shell. Simply click the “Run” button and find the generated CSV files in the “Files” tab.

https://repl.it/@finxter/methodscsvlisto...?lite=true



Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: