0

I'm trying to import a CSV into pandas and view the data frame. I'm following a tutorial that says I can e.g. retrieve the headers via data.head().

This doesn't return anything when I run the program and I have to put print around everything to make it work.

What am I doing wrong?

import os
path = "testdata"
os.chdir(path)
os.getcwd()

data = pd.read_csv("testdata.csv")

print(data.head())

list(data.columns.values)
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • obviously you have to `print` to see what `data.head()` returns that's why `print` is used – Sociopath May 16 '19 at 10:54
  • 2
    You are doing everything correctly. The tutorial perhaps talks about using the interactive python interpreter (running `python` from command line and then writing code) or about using Jupyter Notebook (this one has a built-in feature that automatically prints the last variable even without print). Using the `print()` function is very normal and it's very easy in python considering some other programming languages. –  May 16 '19 at 10:56
  • in normal script you have to use `print()` to display anything - and you can decide what you want to see. In Python Shell or in Jupyter it automatically displays every result to make life easier because in shell/jupyter most people want to see all results. – furas May 16 '19 at 10:57
  • Does this answer your question? [Output shown in Jupyter Notebook but not in Pycharm](https://stackoverflow.com/questions/59231992/output-shown-in-jupyter-notebook-but-not-in-pycharm) – Georgy Oct 09 '20 at 09:02

2 Answers2

1

Your tutorial is expecting that you are typing your Python code at an interpreter's read-execute-display prompt (such as the command-line Python interpreter, or IDLE), normally indicated by >>>. But you are running your code in PyCharm as a program. If you want the behaviour you expect in PyCharm, ask it to open a Python console and type your code there.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
1

You are not doing anything wrong, but you probably don't understand the meaning of return. data.head() returns the first five values of data. However, if you would use it like this:

data.head()

It will return into nothing, so whatever the function returns is discarded. You could either print the data that it returns in the console, like you did:

print(data.head())

Or you could save it in a variable and print that or do something else with it:

someVariable = data.head()
print(someVariable)
# Or do something with someVariable

If you are typing this code in the interpreter, the return value of data.head() would be written to the console automatically. Like this (from this example):

>>> df.head()
      animal
0  alligator
1        bee
2     falcon
3       lion
4     monkey
funie200
  • 3,688
  • 5
  • 21
  • 34