I have microsecond resolution in my df which is very important but no matter what I try, I can't get excel to show microsecond resolution with either .xls or .xlsx. Any ideas on how to get them to display without converting to a string explicitly?
With the latest version of Pandas on GitHub (and in the soon to be released 0.13.1) you can specify the Excel date format in the ExcelWriter() like this:
import pandas as pd
from datetime import datetime
df = pd.DataFrame([datetime(2014, 2, 1, 12, 30, 5, 60000)])
writer = pd.ExcelWriter("time.xlsx", date_format='hh:mm:ss.000')
df.to_excel(writer, "Sheet1")
writer.close()
Which will display the microsecond times (or at least milliseconds since that is Excel's display limit):
See also Working with Python Pandas and XlsxWriter.
Related
I am new to python and exploring to get data from excel using it and found pandas library to get data
I need to get the rates from a HTML table on a website. Table from which the data has to be read
Then dump it in an excel file.
I am using Python
I have used the following code
import pandas as pd
from datetime import datetime
import lxml as lx
import openpyxl as oxl
url = "https://www.example.com"
tables = pd.read_html(url)
table = tables[0]
table.to_excel('output.xlsx')
The dates are in dd mmm yyyy format in the 'Effective Date' column
I would like to convert them to the dd/mm/yyyy format
I used the following code to convert the table
['Effective Date'] = pd.to_datetime(table['Effective Date'],
infer_datetime_format=False, format='%d/%m/%Y', errors='ignore')
but it fails to convert the dates in the column. Could someone head me in some proper direction please.
Here is the complete code
import pandas as pd
import html5lib
import datetime
import locale
import pytz
import lxml as lx
import openpyxl as oxl
url = "https://www.rba.gov.au/statistics/cash-rate/"
tables = pd.read_html(url)
table = tables[0]
table['Effective Date'] = pd.to_datetime(table['Effective Date'],
infer_datetime_format=False, format='%d/%m/%Y', errors='ignore')
table.to_excel('rates.xlsx')
You need to use pd.ExcelWriter to create a writer object, so that you can change to Date format WITHIN Excel; however, this problem has a couple of different aspects to it:
You have non-date values in your date column, including "Legend:", "Cash rate decreased", "Cash Rate increased", and "Cash rate unchanged".
As mentioned in the comments, you must pass format='%d %b %Y' to pd.to_datetime() as that is the Date format you are converting FROM.
You must pass errors='coerce' in order to return NaT for those that don't meet the specified format
For the pd.to_datetime() line of code, you must add .dt.date at the end, because we use a date_format parameter and not a datetime_format parameter in creating the writer object later on. However, you could also exclude dt.date and change the format of the datetime_format parameter.
Then, do table = table.dropna() to drop rows with any columns with NaT
Pandas does not change the Date format WITHIN Excel. If you want to do that, then you should use openpyxl and create a writer object and pass the date_format. In case someone says this, you CANNOT simply do: pd.to_datetime(table['Effective Date'], format='%d %b %Y', errors='coerce').dt.strftime('%m/%d/%y') or .dt.strftime('%d/%m/%y'), because that creates a "General" date format in EXCEL.
Output is ugly if you do not widen your columns, so I've included code for that as well. Please note that I am on a USA locale, so passing d/m/yyyy creates a "Custom" format in Excel.
NOTE: In my code, I have to pass m/d/yyyy in order for a "Date" format to appear in EXCEL. You can simply change to date_format='d/m/yyyy' since my computer has a different locale than you (USA) that Excel utilizes for "Date" format.
Source + More on this topic:
import pandas as pd
import html5lib
import datetime
import locale
import pytz
import lxml as lx
import openpyxl as oxl
url = "https://www.rba.gov.au/statistics/cash-rate/"
tables = pd.read_html(url)
table = tables[0]
table['Effective Date'] = pd.to_datetime(table['Effective Date'], format='%d %b %Y', errors='coerce').dt.date
table = table.dropna()
table.to_excel('rates.xlsx')
writer = pd.ExcelWriter("rates.xlsx",
engine='xlsxwriter',
date_format='m/d/yyyy')
# Convert the dataframe to an XlsxWriter Excel object.
table.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects in order to set the column
# widths, to make the dates clearer.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.set_column('B:E', 20)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
I've locked myself out of pytrends trying to solve this. Found some help in an old post
There are a few elements, firstly, I don't fully understand the documentation e.g. what is the payload? When i run it it doesn't seem to do anything. The result is I'm working with a lot of copy pasted code.
Second, I want to get keyword trend data for the year to date in a .csv
import pandas as pd
from pytrends.exceptions import ResponseError
from pytrends.request import TrendReq
import matplotlib.pyplot as plt
data = []
kw_list = ["maxi dresses", "black shorts"]
for kw in kw_list:
kw_data = dailydata.get_daily_data(kw, 2020, 1, 2020, 4, geo = 'GB')
data.append(kw_data)
data.to_csv(r"C:\Users\XXXX XXXXX\Documents\Python Files\PyTrends\trends_py.csv".)
I also tried:
df =pytrends.get_historical_interest(kw_list, year_start=2020, month_start=1, day_start=1, year_end=2020, month_end=4, geo='GB', gprop='', sleep=0)
df = df.reset_index()
df.head(20)
Though for my purposes get_historical_interest is useless because it provides hourly data with lots of 0s. The hourly data also doesn't match trends.
I am reading in some excel data that contains datetime values stored as '8/13/2019 4:51:00 AM' and formatted as '4:51:00 AM' in excel. I would like to have a data frame that converts the value to a timestamp formatted as '4:51 AM' or H%:M% p%.
I have tried using datetime strptime but I don't believe I have been using it correctly. None of my attempts have worked so I have left it out of the code below. The two columns I would like to convert are 'In Punch' and 'Out Punch'
import pandas as pd
import pymssql
import numpy as np
import xlrd
import os
from datetime import datetime as dt
rpt = xlrd.open_workbook('OpenReport.xls', logfile=open(os.devnull,'w'))
rpt = pd.read_excel(rpt, skiprows=7)[['ID','Employee','Date/Time','In Punch','Out Punch',
'In Punch Comment','Out Punch Comment', 'Totaled Amount']]
rpt
Any suggestions will be greatly appreciated. Thanks
EDIT:
Working with the following modifications now.
rpt['In Punch'] = pd.to_datetime(rpt['In Punch']).dt.strftime('%I:%M %p')
rpt['Out Punch'] = pd.to_datetime(rpt['Out Punch']).dt.strftime('%I:%M %p')
Try working with datetime inside pandas. Convert Pandas Column to DateTime has some good suggestions that could help you out.
rpt['In Punch'] = pd.to_datetime(rpt['In Punch'])
Then you can do all sorts of lovely tweaks to a datetime. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html
I'm importing a csv files which contain a datetime column, after importing the csv, my data frame will contain the Dat column which type is pandas.Series, I need to have another column that will contain the weekday:
import pandas as pd
from datetime import datetime
data =
pd.read_csv("C:/Users/HP/Desktop/Fichiers/Proj/CONSOMMATION_1h.csv")
print(data.head())
all the data are okay, but when I do the following:
data['WDay'] = pd.to_datetime(data['Date'])
print(type(data['WDay']))
# the output is
<class 'pandas.core.series.Series'>
the data is not converted to datetime, so I can't get the weekday.
Problem is you need dt.weekday with .dt:
data['WDay'] = data['WDay'].dt.weekday
Without dt is used for DataetimeIndex (not in your case) - DatetimeIndex.weekday:
data['WDay'] = data.index.weekday
use the command data.dtypes to check the type of the columns.
I'm looking to pull specific information from the table below to use in other functions. For example extracting the volume on 1/4/16 to see if the volume traded is > 1 million. Any thoughts on how to do this would be greatly appreciated.
import pandas as pd
import pandas.io.data as web # Package and modules for importing data; this code may change depending on pandas version
import datetime
1, 2016
start = datetime.datetime(2016,1,1)
end = datetime.date.today()
apple = web.DataReader("AAPL", "yahoo", start, end)
type(apple)
apple.head()
Results:
The datareader will return a df with a datetimeIndex, you can use partial datetime string matching to give you the specific row and column using loc:
apple.loc['2016-04-01','Volume']
To test whether this is larger than 1 million, just compare it:
apple.loc['2016-04-01','Volume'] > 1000000
which will return True or False