Pandas, selec_index.loc [] same sentence, different results when printing

1

I do not understand why I get so disparate results presentations with these two sentences that, in principle, are the same (ini = 0 in the script):

>>> print (selec_index.loc[0, "Fecha"])
2017-09-12 00:00:00

>>> print ("Fecha de inicio del analisis : ", selec_index.loc[ini, "Fecha"])
('Fecha de inicio del analisis : ', Timestamp('2017-09-12 00:00:00'))

On the other hand, how complicated is the handling of dates in python for the most inexperienced! How can I get the date in this "2017-09-12" format instead of "Timestamp ...."?

Do you know any document / Web, that clearly shows exercises of changing from one format to another in Python-Pandas ?. Thanks

    
asked by efueyo 12.11.2017 в 21:00
source

1 answer

1

It is almost certain that you are using Python 2 (in Python 3 this behavior is not the case, at least with the example you provide). Your problem has nothing to do with Pandas or with the treatment of dates by this, it is due to how you use print . In Python 2 print is not a function so you should not use parentheses like in Python 3:

>>> print "hola", 4
hola 4

If you use parentheses and pass at least two objects separated by a comma you are actually creating a tuple and printing it later. When you print a tuple, its elements are shown according to the output of its methods __repr__ instead of __str__ , that's why it prints you Timestamp(...) Look at this post if you are interested in learning more about this:

Why is printing a list different from printing your items separately?

We can see this behavior in a very simple way with the previous example:

>>> print("hola", 4)
('hola', 4)

Just do not use parentheses with print in Python 2, and you'll get the same output in both cases:

>>> import pandas as pd
>>> ini = 0
>>> selec_index = pd.DataFrame(pd.date_range(pd.Timestamp('now'), periods=4),  columns = ["Fecha"])

>>> selec_index
                       Fecha
0 2017-11-12 22:34:09.111527
1 2017-11-13 22:34:09.111527
2 2017-11-14 22:34:09.111527

>>> print selec_index.loc[0, "Fecha"]
2017-11-12 22:32:29.687000
>>> print "Fecha de inicio del analisis : ", selec_index.loc[ini, "Fecha"]
Fecha de inicio del analisis :  2017-11-12 22:32:29.687000

If you want to specify a format to your liking use strftime :

>>> print "Fecha de inicio del analisis : ", selec_index.loc[ini, "Fecha"].strftime('%d/%m/%Y')
Fecha de inicio del analisis :  12/11/2017
>>> print "Fecha de inicio del analisis : ", selec_index.loc[ini, "Fecha"].strftime('%Y-%m-%d')
Fecha de inicio del analisis :  2017-11-12
    
answered by 12.11.2017 / 22:41
source