I want to check in my dataframe's column that if there is a missing date for a certain month then the code should output the following month in the format MMM- YYYY
The data set looks like this :
date_start_balance date_end_balance start_balance
22.02.16 22.03.16 3590838
22.04.16 22.05.16 69788
15.06.16 21.07.16 452165
Both date cols are in datetime format. Now in the above data set the dates are missing for March and May in the start col and this should be returned as MMM-YYYYY
I have tried the following code :
import datetime
dates = df1['date_start_balance'].tolist()
missing = []
for i in range(0,len(dates)-1):
if dates[i+1].month - dates[i+1].month != 1:
for j in range(dates[i].month+1,dates[i+1].month):
missing.append(datetime(dates[i].year, j,1))
print(missing)
You can first create a date range with pd.date_range
march = pd.date_range(start='2016-05-01', end='2016-05-31')
And then you will have the list with the dates that you already have, in the example there is only one date: 2016-05-15:
your_list = [datetime.datetime.strptime('15052016', "%d%m%Y").date()]
And then you can calculate the difference between the range and your list and get the dates that you are missing:
march.difference(your_list)
DatetimeIndex(['2016-05-01', '2016-05-02', '2016-05-03', '2016-05-04',
'2016-05-05', '2016-05-06', '2016-05-07', '2016-05-08',
'2016-05-09', '2016-05-10', '2016-05-11', '2016-05-12',
'2016-05-13', '2016-05-14', '2016-05-16', '2016-05-17',
'2016-05-18', '2016-05-19', '2016-05-20', '2016-05-21',
'2016-05-22', '2016-05-23', '2016-05-24', '2016-05-25',
'2016-05-26', '2016-05-27', '2016-05-28', '2016-05-29',
'2016-05-30', '2016-05-31'],
dtype='datetime64[ns]', freq=None)
Related
I am using pandas pd.bdate_range() to generate a range of dates given a start and end, but it seems to not work as expected.
What I am ultimately after is quarterly dates over a start and end date, but I want the dates to be valid business days.
start = '2015-06-01'
end = '2019-06-01'
dates = pd.bdate_range(start,end,freq='MS')[::3]
unfortunately this includes 2018-09-01 which is a Saturday
is there a more foolproof way to get an index of only business days, also taking account USFederalHolidayCalendar()?
You can take your existing Series and increment to the next business day like so
from pandas.tseries.offsets import BDay
start = '2015-06-01'
end = '2019-06-01'
dates = pd.bdate_range(start,end,freq='MS')[::3]
new_dates = dates.map(lambda x : x + 0*BDay())
Or you can pass BMS to the freq keyword attribute like so
start = '2015-06-01'
end = '2019-06-01'
dates = pd.bdate_range(start,end, freq='BMS')[::3]
Both give this output
DatetimeIndex(['2015-06-01', '2015-09-01', '2015-12-01', '2016-03-01',
'2016-06-01', '2016-09-01', '2016-12-01', '2017-03-01',
'2017-06-01', '2017-09-01', '2017-12-01', '2018-03-01',
'2018-06-01', '2018-09-03', '2018-12-03', '2019-03-01',
'2019-06-03'],
dtype='datetime64[ns]', freq=None)
I think you can pass the following to get what you desire.
freq='BMS' # Business month start
or
freq='BQS' # Business quarter start
Update:
You could do something like this take care of holidays that fall on month/quarter start.
from pandas import DatetimeIndex
from pandas.tseries.holiday import USFederalHolidayCalendar
holidays = USFederalHolidayCalendar().holidays(start, end, return_name=False)
month_dates = pandas.bdate_range(start, end, freq='CBMS', holidays=[holiday for holiday in holidays])
print(month_dates)
print(DatetimeIndex([e[1] for e in zip(month_dates.month, month_dates) if e[0] in {1, 4, 7, 10}]))
DatetimeIndex(['2015-01-02', '2015-02-02', '2015-03-02', '2015-04-01',
'2015-05-01', '2015-06-01', '2015-07-01', '2015-08-03',
'2015-09-01', '2015-10-01', '2015-11-02', '2015-12-01',
'2016-01-04', '2016-02-01', '2016-03-01', '2016-04-01',
'2016-05-02', '2016-06-01', '2016-07-01', '2016-08-01',
'2016-09-01', '2016-10-03', '2016-11-01', '2016-12-01',
'2017-01-03', '2017-02-01', '2017-03-01', '2017-04-03',
'2017-05-01', '2017-06-01', '2017-07-03', '2017-08-01',
'2017-09-01', '2017-10-02', '2017-11-01', '2017-12-01',
'2018-01-02', '2018-02-01', '2018-03-01', '2018-04-02',
'2018-05-01', '2018-06-01', '2018-07-02', '2018-08-01',
'2018-09-04', '2018-10-01', '2018-11-01', '2018-12-03',
'2019-01-02', '2019-02-01', '2019-03-01', '2019-04-01',
'2019-05-01'],
dtype='datetime64[ns]', freq='CBMS')
DatetimeIndex(['2015-01-02', '2015-04-01', '2015-07-01', '2015-10-01',
'2016-01-04', '2016-04-01', '2016-07-01', '2016-10-03',
'2017-01-03', '2017-04-03', '2017-07-03', '2017-10-02',
'2018-01-02', '2018-04-02', '2018-07-02', '2018-10-01',
'2019-01-02', '2019-04-01'],
dtype='datetime64[ns]', freq=None)
date = ['2010-01-11' '2010-01-12' '2010-01-13' '2010-01-14' '2010-01-15'
'2010-01-16' '2010-01-17' '2010-01-18' '2010-01-19' '2010-01-20'
'2010-01-21' '2010-01-22' '2010-01-23' '2010-01-24' '2010-01-25'
'2010-01-26' '2010-01-27' '2010-01-28' '2010-01-29' '2010-01-30'
'2010-01-31' '2010-02-01' '2010-02-02' '2010-02-03' '2010-02-04'
'2010-02-05' '2010-02-06' '2010-02-07' '2010-02-08' '2010-02-09'
'2010-02-10' '2010-02-11' '2010-02-12' '2010-02-13' '2010-02-14'
'2010-02-15' '2010-02-16' '2010-02-17' '2010-02-18' '2010-02-19'
'2010-02-20' '2010-02-21' '2010-02-22' '2010-02-23' '2010-02-24'
'2010-02-25' '2010-02-26' '2010-02-27' '2010-02-28' '2010-03-01'
'2010-03-02' '2010-03-03' '2010-03-04' '2010-03-05' '2010-03-06'
'2010-03-07' '2010-03-08' '2010-03-09' '2010-03-10' '2010-03-11'
'2010-03-12' '2010-03-13' '2010-03-14' '2010-03-15' '2010-03-16'
'2010-03-17' '2010-03-18' '2010-03-19' '2010-03-20' '2010-03-21'
'2010-03-22' '2010-03-23' '2010-03-24' '2010-03-25' '2010-03-26'
'2010-03-27' '2010-03-28' '2010-03-29' '2010-03-30' '2010-03-31'
'2010-04-01' '2010-04-02' '2010-04-03' '2010-04-04' '2010-04-05'
'2010-04-06' '2010-04-07' '2010-04-08' '2010-04-09' '2010-04-10'
'2010-04-11' '2010-04-12' '2010-04-13' '2010-04-14' '2010-04-15'
'2010-04-16' '2010-04-17' '2010-04-18' '2010-04-19' '2010-04-20'
'2010-04-21' '2010-04-22' '2010-04-23' '2010-04-24' '2010-04-25'
'2010-04-26' '2010-04-27' '2010-04-28' '2010-04-29' '2010-04-30'
'2010-05-01' '2010-05-02' '2010-05-03' '2010-05-04' '2010-05-05'
'2010-05-06' '2010-05-07' '2010-05-08' '2010-05-09' '2010-05-10'
'2010-05-11' '2010-05-12' '2010-05-13' '2010-05-14' '2010-05-15'
'2010-05-16' '2010-05-17' '2010-05-18' '2010-05-19' '2010-05-20'
'2010-05-21' '2010-05-22' '2010-05-23' '2010-05-24' '2010-05-25'
'2010-05-26' '2010-05-27' '2010-05-28' '2010-05-29' '2010-05-30'
'2010-05-31' '2010-06-01' '2010-06-02' '2010-06-03' '2010-06-04'
'2010-06-05' '2010-06-06' '2010-06-07' '2010-06-08' '2010-06-09'
'2010-06-10' '2010-06-11' '2010-06-12' '2010-06-13' '2010-06-14'
'2010-06-15' '2010-06-16' '2010-06-17' '2010-06-18' '2010-06-19'
'2010-06-20' '2010-06-21' '2010-06-22' '2010-06-23' '2010-06-24'
'2010-06-25' '2010-06-26' '2010-06-27' '2010-06-28' '2010-06-29'
'2010-06-30']
cant seem to figure out the coding to extract the last day of each month in the above list. please note that the last day of each month in the above list does not necessary equivalent to the last day of each calender month.
Expected output:
['2010-01-29', '2010-02-26', '2010-03-31', '2010-04-30', '2010-05-28', '2010-06-30']
saw some solution as follows but it does not return to an valid outcome:
date = date - pd.tseries.offsets.MonthEnd()
previous_month = '01'
last_trading_days = []
for index, day in enumerate(date):
# Extract month from date
month = day[5:7]
# If this is the first day of the new month, append the day that came before it
if month != previous_month:
previous_month = month
last_trading_days.append(date[index - 1])
# Also append the last day
if index == len(date) - 1:
last_trading_days.append(day)
print(last_trading_days)
This is if you know the first month will be January, otherwise you can use previous_month = date[0][5:7] to start on the month of the first date in the list.
Download stock data for each last trading day of the month till date:
df = yf.download(symbol,period='max')
df = df.groupby(df.index.strftime('%Y-%m')).tail(1)
I want to import this kind of csv into Excel
Work Item Type,ID,State,Date Request,Created Date
"Task","4533","Closed","2-9-2020 14:26:00","3-9-2020 08:17:39"
"Task","4535","Closed","3-9-2020 12:26:44","3-9-2020 12:29:33"
"Task","4577","Closed","3-9-2020 15:56:00","4-9-2020 09:12:21"
"Task","4580","New","17-8-2020 09:47:00","4-9-2020 09:49:39"
"Task","4581","Resolved","28-8-2020 10:22:00","4-9-2020 10:24:46"
"Task","4582","Resolved","24-8-2020 10:05:00","4-9-2020 10:31:12"
"Task","4604","Resolved","8-9-2020 08:06:58","8-9-2020 08:07:23"
"Task","4605","Resolved","8-9-2020 09:18:32","8-9-2020 09:18:58"
All dates in this example must be seen with a format day-month-year hour:minute:second
I do the import like this:
Import-Csv -Path '.\Issues.csv' | ForEach-Object {
$sheet1.Cells.Item(1,1) = 'ID'
$sheet1.Cells.Item(1,2) = 'Status'
$sheet1.Cells.Item(1,3) = 'Date Request'
$sheet1.Cells.Item(1,4) = 'Date Created'
$DateRequest = ([datetime]::ParseExact(($($_."Date Request")),$fmtDate,$inv).ToString($fmtDate))
$sheet1.Cells.Item($row,1) = $($_.ID)
$sheet1.Cells.Item($row,2) = $($_.State)
$sheet1.Cells.Item($row,3) = $($_."Date Request")
$sheet1.Cells.Item($row,4) = $($_."Created Date")
$row = $row + 1
}
The result of my Import
ID Status Date Request Date Created
4533 Closed 9/02/2020 14:26 9/03/2020 8:17
4535 Closed 9/03/2020 12:26 9/03/2020 12:29
4577 Closed 9/03/2020 15:56 9/04/2020 9:12
4580 New 17-8-2020 09:47:00 9/04/2020 9:49
4581 Resolved 28-8-2020 10:22:00 9/04/2020 10:24
4582 Resolved 24-8-2020 10:05:00 9/04/2020 10:31
4604 Resolved 9/08/2020 8:06 9/08/2020 8:07
4605 Resolved 9/08/2020 9:18 9/08/2020 9:18
As you can see, some dates are red in the CSV with a month-day-year format,
other are red with a day-month-year format.
The date 3 september has become 9 march
I have tried using CultureInfo, but without any succes.
$inv = [System.Globalization.CultureInfo]::InvariantCulture<br>
$fmtDate = "dd/MM/YYYY HH:mm:ss"
$DateRequest = ([datetime]::ParseExact(($($_."Date Request")),$fmtDate,$inv).ToString($fmtDate))
Does anyone hove any suggestions to solve this?
First of all, the dates in your CSV file have this format d-M-yyyy HH:mm:ss (yyyy is in lowercase and the days and months in the fields do not have a leading zeroes).
Try
$fmtDate = "d-M-yyyy HH:mm:ss"
What puzzles me is why you want to first parse the date in the csv and then use ToString() to reformat it in the exact same string format.
Take off the .ToString($fmtDate) as in
$DateRequest = [datetime]::ParseExact($_."Date Request",$fmtDate, $inv)
and feed that DateTime object into the Excel cell
dd/MM/YYYY HH:mm:ss does NOT describe the input date format you have - dd and MM are for day and month numbers with leading zeros.
Use:
$fmtDateInput = 'd-M-yyyy HH:mm:ss'
$fmtDateOutput = "dd/MM/yyyy HH:mm:ss"
[datetime]::ParseExact($dateString, $fmtDateInput, $culture).ToString($fmtDateOutput)
I am trying to replace the values of 3 columns within multiple observations based on two conditionals ( e.g., specific ID after a particular date).
I have seen similar questions.
Pandas Multiple Conditions Function based on Column
Pandas replace, multi column criteria
Pandas: How do I assign values based on multiple conditions for existing columns?
Replacing values in a pandas dataframe based on multiple conditions
However, they did not quite address my problem or I can't quite manipulate them to solve my problem.
This code will generate a dataframe similar to mine:
df = pd.DataFrame({'SUR_ID': {0:'SUR1', 1:'SUR1', 2:'SUR1', 3:'SUR1', 4:'SUR2', 5:'SUR2'}, 'DATE': {0:'05-01-2019', 1:'05-11-2019', 2:'06-15-2019', 3:'06-20-2019', 4: '05-15-2019', 5:'06-20-2019'}, 'ACTIVE_DATE': {0:'05-01-2019', 1:'05-01-2019', 2:'05-01-2019', 3:'05-01-2019', 4: '05-01-2019', 5:'05-01-2019'}, 'UTM_X': {0:'444895', 1:'444895', 2:'444895', 3:'444895', 4: '445050', 5:'445050'}, 'UTM_Y': {0:'4077528', 1:'4077528', 2:'4077528', 3:'4077528', 4: '4077762', 5:'4077762'}})
Output Dataframe:
What I am trying to do:
I am trying to replace UTM_X,UTM_Y, AND ACTIVE_DATE with
[444917, 4077830, '06-04-2019']
when
SUR_ID is "SUR1" and DATE >= "2019-06-04 12:00:00"
This is a poorly adapted version of the solution for question 1 in attempts to fix my problem- throws error:
df.loc[[df['SUR_ID'] == 'SUR1' and df['DATE'] >='2019-06-04 12:00:00'], ['UTM_X', 'UTM_Y', 'Active_Date']] = [444917, 4077830, '06-04-2019']
First ensure that the column Date is of type datetime, and then when using 2 conditions, they need to be between parenthesis individually. so you can do:
df.DATE = pd.to_datetime(df.DATE)
df.loc[ (df['SUR_ID'] == 'SUR1') & (df['DATE'] >= pd.to_datetime('2019-06-04 12:00:00')),
['UTM_X', 'UTM_Y', 'ACTIVE_DATE']] = [444917, 4077830, '06-04-2019']
See the difference between what you wrote for the boolean mask:
[df['SUR_ID'] == 'SUR1' and df['DATE'] >='2019-06-04 12:00:00']
and what is here with parenthesis
(df['SUR_ID'] == 'SUR1') & (df['DATE'] >= pd.to_datetime('2019-06-04 12:00:00'))
Use:
df['UTM_X']=df['UTM_X'].mask(df['SUR_ID'].eq('SUR1') & (pd.to_datetime(df['DATE'])>= pd.to_datetime("2019-06-04 12:00:00")),444917)
df['UTM_Y']=df['UTM_Y'].mask(df['SUR_ID'].eq('SUR1') & (pd.to_datetime(df['DATE'])>= pd.to_datetime("2019-06-04 12:00:00")),4077830)
df['ACTIVE_DATE']=df['ACTIVE_DATE'].mask(df['SUR_ID'].eq('SUR1') & (pd.to_datetime(df['DATE'])>= pd.to_datetime("2019-06-04 12:00:00")),'06-04-2019')
Output:
SUR_ID DATE ACTIVE_DATE UTM_X UTM_Y
0 SUR1 05-01-2019 05-01-2019 444895 4077528
1 SUR1 05-11-2019 05-01-2019 444895 4077528
2 SUR1 06-15-2019 06-04-2019 444917 4077830
3 SUR1 06-20-2019 06-04-2019 444917 4077830
4 SUR2 05-15-2019 05-01-2019 445050 4077762
5 SUR2 06-20-2019 05-01-2019 445050 4077762
I have a list that has several days in it. Each day have several timestamps. What I want to do is to make a new list that only takes the start time and the end time in the list for each date.
I also want to delete the Character between the date and the time on each one, the char is always the same type of letter.
the time stamps can vary in how many they are on each date.
Since I'm new to python it would be preferred to use a lot of simple to understand codes. I've been using a lot of regex so pleas if there is a way with this one.
the list has been sorted with the command list.sort() so it's in the correct order.
code used to extract the information was the following.
file1 = open("test.txt", "r")
for f in file1:
list1 += re.findall('20\d\d-\d\d-\d\dA\d\d\:\d\d', f)
listX = (len(list1))
list2 = list1[0:listX - 2]
list2.sort()
here is a list of how it looks:
2015-12-28A09:30
2015-12-28A09:30
2015-12-28A09:35
2015-12-28A09:35
2015-12-28A12:00
2015-12-28A12:00
2015-12-28A12:15
2015-12-28A12:15
2015-12-28A14:30
2015-12-28A14:30
2015-12-28A15:15
2015-12-28A15:15
2015-12-28A16:45
2015-12-28A16:45
2015-12-28A17:00
2015-12-28A17:00
2015-12-28A18:15
2015-12-28A18:15
2015-12-29A08:30
2015-12-29A08:30
2015-12-29A08:35
2015-12-29A08:35
2015-12-29A10:45
2015-12-29A10:45
2015-12-29A11:00
2015-12-29A11:00
2015-12-29A13:15
2015-12-29A13:15
2015-12-29A14:00
2015-12-29A14:00
2015-12-29A15:30
2015-12-29A15:30
2015-12-29A15:45
2015-12-29A15:45
2015-12-29A17:15
2015-12-29A17:15
2015-12-30A08:30
2015-12-30A08:30
2015-12-30A08:35
2015-12-30A08:35
2015-12-30A10:45
2015-12-30A10:45
2015-12-30A11:00
2015-12-30A11:00
2015-12-30A13:00
2015-12-30A13:00
2015-12-30A13:45
2015-12-30A13:45
2015-12-30A15:15
2015-12-30A15:15
2015-12-30A15:30
2015-12-30A15:30
2015-12-30A17:15
2015-12-30A17:15
And this is how I want it to look like:
2015-12-28 09:30
2015-12-28 18:15
2015-12-29 08:30
2015-12-29 17:15
2015-12-30 08:30
2015-12-30 17:15
First of all, you should convert all your strings into proper dates, Python can work with. That way, you have a lot more control on it, also to change the formatting later. So let’s parse your dates using datetime.strptime in list2:
from datetime import datetime
dates = [datetime.strptime(item, '%Y-%m-%dA%H:%M') for item in list2]
This creates a new list dates that contains all your dates from list2 but as parsed datetime object.
Now, since you want to get the first and the last date of each day, we somehow have to group your dates by the date component. There are various ways to do that. I’ll be using itertools.groupby for it, with a key function that just looks at the date component of each entry:
from itertools import groupby
for day, times in groupby(dates, lambda x: x.date()):
first, *mid, last = times
print(first)
print(last)
If we run this, we already get your output (without date formatting):
2015-12-28 09:30:00
2015-12-28 18:15:00
2015-12-29 08:30:00
2015-12-29 17:15:00
2015-12-30 08:30:00
2015-12-30 17:15:00
Of course, you can also collect that first and last date in a list first to process the dates later:
filteredDates = []
for day, times in groupby(dates, lambda x: x.date()):
first, *mid, last = times
filteredDates.append(first)
filteredDates.append(last)
And you can also output your dates with a different format using datetime.strftime:
for date in filteredDates:
print(date.strftime('%Y-%m-%d %H:%M'))
That would give us the following output:
2015-12-28 09:30
2015-12-28 18:15
2015-12-29 08:30
2015-12-29 17:15
2015-12-30 08:30
2015-12-30 17:15
If you don’t want to go the route through parsing those dates, of course you could also do this simply by working on the strings. Since they are nicely formatted (i.e. they can be easily compared), you can do that as well. It would look like this then:
for day, times in groupby(list2, lambda x: x[:10]):
first, *mid, last = times
print(first)
print(last)
Producing the following output:
2015-12-28A09:30
2015-12-28A18:15
2015-12-29A08:30
2015-12-29A17:15
2015-12-30A08:30
2015-12-30A17:15
Because your data is ordered you just need to pull the first and last value from each group, you can use re.sub to remove the single letter replacing it with a space then split each date string just comparing the dates:
from re import sub
def grp(l):
it = iter(l)
prev = start = next(it).replace("A"," ")
for dte in it:
dte = dte.replace("A"," ")
# if we have a new date, yield that start and end
if dte.split(None, 1)[0] != prev.split(None,1)[0]:
yield start
yield prev
start = dte
prev = dte
yield start, prev
l=["2015-12-28A09:30", "2015-12-28A09:30", .....................
l[:] = grp(l)
This could also certainly be done as your process the file without sorting by using a dict to group:
from re import findall
from collections import OrderedDict
with open("dates.txt") as f:
od = defaultdict(lambda: {"min": "null", "max": ""})
for line in f:
for dte in findall('20\d\d-\d\d-\d\dA\d\d\:\d\d', line):
dte, tme = dte.split("A")
_dte = "{} {}".format(dte, tme)
if od[dte]["min"] > _dte:
od[dte]["min"] = _dte
if od[dte]["max"] < _dte:
od[dte]["max"] = _dt
print(list(od.values()))
Which will give you the start and end time for each date.
[{'min': '2016-01-03 23:59', 'max': '2016-01-03 23:59'},
{'min': '2015-12-28 00:00', 'max': '2015-12-28 18:15'},
{'min': '2015-12-30 08:30', 'max': '2015-12-30 17:15'},
{'min': '2015-12-29 08:30', 'max': '2015-12-29 17:15'},
{'min': '2015-12-15 08:41', 'max': '2015-12-15 08:41'}]
The start for 2015-12-28 is also 00:00 not 9:30.
if you dates are actually as posted one per line you don't need a regex either:
from collections import defaultdict
with open("dates.txt") as f:
od = defaultdict(lambda: {"min": "null", "max": ""})
for line in f:
dte, tme = line.rstrip().split("A")
_dte = "{} {}".format(dte, tme)
if od[dte]["min"] > _dte:
od[dte]["min"] = _dte
if od[dte]["max"] < _dte:
od[dte]["max"] = _dte
print(list(od.values()
Which would give you the same output.