logo
Tags down

shadow

How do I sum an amount field for the last week of each month in python?


By : Martin
Date : August 01 2020, 10:00 PM
help you fix your problem Instead of manually specifying the dates you can use pd.offsets.MonthEnd, together with a subtraction to get the number of days from the end of the month. Then susbet and group
code :
s = ((df['date'] + pd.offsets.MonthEnd(0)) - df['date']).dt.days

Ndays = 7  # This many from the end
df[s.lt(Ndays)].groupby(df['date'].dt.to_period('M')).sum()
         amount
date           
2019-01     247
2019-02     420
2019-03     223
2019-04     387
2019-05     382
2019-06     240
2019-07     410
2019-08     365
2019-09     344
2019-10     444
2019-11     274
2019-12     339
2020-01     391
2020-02     131


Share : facebook icon twitter icon

Java Calendar shows wrong amount of weeks when first week of month is defined as week in which 1 occurs


By : Dusan Katona
Date : March 29 2020, 07:55 AM
this one helps. It sounds to me like you should:
Work out the first day of the month Determine from that how many "extra" days are "borrowed" from the previous month (e.g. 0 if day 1 is a Monday; 1 if day 1 is a Tuesday etc) Add that to the number of days in the regular month Divide by 7 (with implicit truncation towards 0)
code :
// Note: day-of-week runs from Sunday (1) to Saturday (7).
// Entry 0 here is not used. We could do this without an array lookup
// if desired, but it's whatever code you think is clearest.
private static final int[] EXTRA_DAYS = { 0, 6, 0, 1, 2, 3, 4, 5 };

// Note: 0-based month as per the rest of java.util.Calendar
public static int getWeekCount(int year, int month) {
    Calendar calendar = new GregorianCalendar(year, month, 1);
    int dayOfWeekOfStartOfMonth = calendar.get(Calendar.DAY_OF_WEEK);
    int extraDays = EXTRA_DAYS[dayOfWeekOfStartOfMonth];
    int regularDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    int effectiveDaysInMonth = regularDaysInMonth + extraDays;
    return effectiveDaysInMonth / 7;
}

Get sum of amount records as each row is month and column is week using sql?


By : Tony Hogan
Date : March 29 2020, 07:55 AM
Does that help I suppose weeks numeration needed like this:
code :
;WITH cte AS (
SELECT MONTH(Date_Val) as [MonthNum],
       DATENAME(month,Date_Val) as [Month],
       DATEPART(week,Date_Val) as [ActualWeekNum],
       FLOOR((CAST(DATEPART(week,Date_Val) as decimal(5,2))/4- FLOOR(CAST(DATEPART(week,Date_Val) as decimal(5,2))/4))*100) as [Week],
       Amount as [Amount]
FROM  TBL_yearlyReport
WHERE  YEAR(Date_Val) = 2012
)

SELECT [Month],Week1,Week2,Week3,Week4
FROM
(
SELECT [MonthNum],
       [Month],
       CASE WHEN [Week] = 25 THEN 'Week1' 
            WHEN [Week] = 50 THEN 'Week2'
            WHEN [Week] = 75 THEN 'Week3' 
            WHEN [Week] = 0  THEN 'Week4'
            ELSE NULL
            END as [Week],
       Amount 
FROM cte
) d
pivot
(
SUM(Amount) for [WEEK] in (Week1,Week2,Week3,Week4)
) piv
ORDER BY [MonthNum];
    Month                          Week1       Week2       Week3       Week4
------------------------------ ----------- ----------- ----------- -----------
January                        1995        4798        5280        4500
February                       6102        4283        4039        4519
March                          7445        2616        5701        5977
April                          4991        5624        4823        4901
May                            3826        5858        1970        3703
June                           3461        3950        4208        1707
July                           2970        2469        5217        2861
August                         2536        2535        4887        2210
September                      2352        2721        4232        3165
October                        2876        3044        4702        7160
November                       3183        3158        4509        5507
December                       3666        3509        3276        3257

How to find all week numbers that are first week of month in a year python


By : Abhishek Prasad
Date : March 29 2020, 07:55 AM
To fix the issue you can do I've done a loop through the months, then got the first Sunday (starting at month's 1st and moving to the next day until a Sunday is found), then got the week-of-year of the date found:
code :
from datetime import datetime
from datetime import date

# dayofweek: Sunday=0, Monday=1 and so on
def get_week_number(year=2017, dayofweek=0):
    weeks = []

    for month in range(1, 13):
        # get first Sunday of month
        d = date(year, month, 1)
        while(d.weekday() != dayofweek):
            d = d.replace(day=d.day + 1)

        # isocalendar()[1] is the week-of-year field
        weeks.append(d.isocalendar()[1])

    return weeks

print(get_week_number(2017, 0))
[1, 6, 10, 14, 18, 23, 27, 32, 36, 40, 45, 49]

Fullcalendar using week view, navigate month by month instead of week by week


By : Đức Tuấn Kupj
Date : March 29 2020, 07:55 AM
To fix this issue That one was fun! So the trick is to hide the .fc-week rows we don't want to see in a month view. Then, we don't have to mess with the normal navigation.
To do this, we have to target which row we want to see. I made 2 options here:
code :
// Switches about what to display
// Use only one of the two to true.
var FIND_first_full_week = true;
var FIND_first_day_of_month = false;


$("#calendar").fullCalendar({

  viewRender: function(){
    var ShowWeek;
    var weeks = $(".fc-week");

    // Find the first day of the month
    if(FIND_first_day_of_month){
      for(i=0;i<weeks.length;i++){
        var days = weeks.eq(i).find(".fc-day-number");
        days.each(function(){
          if( $(this).html()=="1" && !$(this).parent().is(".fc-other-month") ){
            ShowWeek = i;
          }
        });
      }
    }
    
    // Find first full week of the month (no day in past month)
    if(FIND_first_full_week){
      for(i=0;i<weeks.length;i++){
        var firstFullWeek = false;
        var dayCount=0;

        var days = weeks.eq(i).find(".fc-day-number");
        days.each(function(){
          if(!firstFullWeek){
            if( !$(this).parent().is(".fc-other-month") ){
              dayCount++;
              if(dayCount==7){
                firstFullWeek = true;
                ShowWeek = i;
                i = weeks.length;
              }
            }
          }
        });
      }
    }
    
    // Fix FullCalendar display!
    setTimeout(function(){
      weeks.not(weeks.eq(ShowWeek)).css({"display":"none"});
      var weekHeight = weeks.height();
      $(".fc-day-grid-container").css({"height":weekHeight});
    },10);
  }
});
/* Your CSS */
.fc td {
  border-bottom: 0 !important;
  border-top: 0 !important;
}

.fc-head {
  border-top: 1px solid black !important;
  border-bottom: 1px solid black !important;
}
.fc-body{
  border-bottom: 1px solid black !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>

<div id="calendar"></div>

JavaScript sort date according to week and month to sum up the amount


By : fudzya
Date : March 29 2020, 07:55 AM
Any of those help To sort by date, use arr.sort(), which will sort it in place so you won't need another array :
code :
arr.sort(function(a,b){
    return new Date(a.date)-new Date(b.date);
});
arr.sort((a,b)=>new Date(a.date)-new Date(b.date));
var arr = [
  {date: '2017/12/16',  profit: 12.50},
  {date: '2017/05/01', profit: 13.50},
  {date: '2017/04/20', profit: 14.50},
  {date: '2017/03/10', profit: 15.50},
  {date: '2017/08/15', profit: 16.50},
  {date: '2017/08/16', profit: 26.50},
  {date: '2017/08/24', profit: 16.50},
  {date: '2017/08/25', profit: 36.50},
  {date: '2017/03/06', profit: 17.50},
  {date: '2017/02/04', profit: 18.50},
  {date: '2017/01/07', profit: 19.50}
];

var profits = [0,0,0,0]; // this/last week, this/last month
var date;

function isThisWeek(d) {
  // start and end of this week
  var thisWeek = [moment().utc().startOf('week'),
                  moment().utc().endOf('week')];
  return d.isBetween(thisWeek[0],thisWeek[1])||
  d.isSame(thisWeek[0])||
  d.isSame(thisWeek[1]);
}

function isLastWeek(d) {
  // start and end of this week minus 1, which is last week
  var lastWeek = [moment().utc().subtract(1,'weeks').startOf('week'),
                  moment().utc().subtract(1,'weeks').endOf('week')];
  return d.isBetween(lastWeek[0],lastWeek[1])||
  d.isSame(lastWeek[0])||
  d.isSame(lastWeek[1]);
}

function isThisMonth(d) {
  // start and end of this month
  var thisMonth = [moment().utc().startOf('month'),
                   moment().utc().endOf('month')];
  return d.isBetween(thisMonth[0],thisMonth[1])||
  d.isSame(thisMonth[0])||
  d.isSame(thisMonth[1]);
}

function isLastMonth(d) {
  // start and end of this month minus 1, which is last month
  var lastMonth = [moment().subtract(1,'months').utc().startOf('month'),
                   moment().subtract(1,'months').utc().endOf('month')];
  return d.isBetween(lastMonth[0],lastMonth[1])||
  d.isSame(lastMonth[0])||
  d.isSame(lastMonth[1]);
}
arr.forEach(function(e){
  date=moment.utc(e.date,'YYYY-MM-DD');
  if (isThisWeek(date)) { // if it's this week
    profits[0]+=e.profit;
  } else if (isLastWeek(date)) { // if it's last week
    profits[1]+=e.profit;
  }
  if (isThisMonth(date)) { // if it's this month
    profits[2]+=e.profit;
  } else if (isLastMonth(date)) { // if it's last month
    profits[3]+=e.profit;
  }
});
console.log("This week profits : "+profits[0]);
console.log("Last week profits : "+profits[1]);
console.log("This month profits : "+profits[2]);
console.log("Last month profits : "+profits[3]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Related Posts Related Posts :
  • How can I assign varaibles to json response?
  • name 'df' is not defined in box plot
  • Comparing dataframe columns
  • Can I Override Global Authentication for a Single Request Type in an ApiView using DRF?
  • Celery chain performances
  • Why am I getting "asynchronous comprehension outside of an asynchronous function"?
  • Creating a file from a docker container
  • doing too many write operations in django rest framework and postgres
  • How to change the order of bar charts in Python?
  • Pandas Data Frame manipulation
  • an undefined error in a simple python code- KeyError: '284882215'
  • Pandas split column in several columns throug string replacement or regex
  • how value is passed from __init__ method in pyhton as it dose not return anyhting
  • Dynamically inherit all Python magic methods from an instance attribute
  • Asking user to input certain information
  • how to test a deep learning model in a new dataset
  • Is np.fft.fft working properly? I am getting very large frequency values
  • How can you delete similar characters at the same positions in 2 strings
  • Does insert (at the end of a list) have O(1) time complexity?
  • Automatically Creating List of Dictionaries Based Upon Two Lists of Equal Length with Python
  • Discrete Cosine Transform (DCT) Coefficient Distribution
  • multiprocessing.Pool not running on last element of iterable
  • Python: sorting string non lexicographically
  • Render images from media directory Django
  • Cannot understand why more vectorization is slower than less vectorization in this case?
  • Django - Use a property as a foreign key
  • creating a function that loops if you do not enter the correct variables
  • Confused on how to store 3D matrices in HDF5 file in matlab?
  • TOTP: Can someone use the same otp within 30s and misuse it
  • is it possible to have 2 type hints for 1 parameter in Python?
  • Can someone explain what this Numpy array property is called?
  • Better way to add the result of apply (multiple outputs) to an existing DataFrame with column names
  • Selecting choice numbers
  • Create variables from list PYTHON
  • This code takes forever to run but doesn't give an error
  • "return" and "return None" behavior difference in generator
  • AttributeError: 'str' object has no attribute 'fbind' error using kivy in Python
  • Python not importing files when not inside conda environment
  • Is it possible to override a class' __call__ method?
  • Python library for live coordinated plotting in map
  • Pandas: counting consecutive rows with condition
  • How to define that a return type of method is an implementation of superclass
  • How can I print to the Visual Studio Code console in Portuguese?
  • Google Appengine Standard Python 2.7: Can't run Google Endpoints on localhost dev_appserver.py anymore
  • google appengine Unauthorized status 401
  • Don't understand cause of this IndentationError in my tic tac toe script
  • How to read in key-value pair from a json file as a pandas dataframe?
  • Can decorator decorate a recursive function?
  • How do I create a nested for loop where I have control of the initial loop index value
  • Unexpected error when creating a SQLite database using python
  • Pythonic way to write cascading of loops and if statements?
  • Python Beginner - Having trouble with multiple choice quiz program
  • Itertools return value NOT used in combinations
  • Return a list of words that contain a letter
  • From rows to columns using Peewee ORM
  • Parse large text document, to keep only "account number", and a specific keyword ("Market Value")
  • Cannot append to my list without getting a nonetype object error
  • Python Train Test Split
  • Optimizing following Python List of Dictionary operation with better solution
  • In Pandas merge colum1 value with colum2, both col data type is object and only few values are null in first column?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org