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 :
  • Convert a CSV-File to a Pandas df via the Gmail API
  • Creating a table from a panda dataframe
  • Converting string date to a date and dropping the time in a dataframe
  • Comma in numbers causing problem reading csv
  • Scatterplot in seaborn 0.8
  • Update whole table to apply new custom save() method
  • Web scraping from the list of urls with python
  • Player walks through wall in a maze Python 3.8 pygame
  • How can I format this, so I don't get an error? math.cos() error
  • I need to be able to 'rotate' a list thats in a 'square' looking formation into a diamond shape python
  • Nested list into list of arguments inside nested list
  • Error in python: "cannot unpack non-iterable NoneType object"
  • How to get the List name that is in a list - python
  • An attribute is a variable?
  • Controlling numpy random seed with variable calls to random size
  • How to increase the number of running containers of spark application using EMR cluster?
  • Read a specific line from a text file then check if it's equal to a string variable?
  • Python dictionary update: content overwritten
  • Getting error message trying to use defined functions for simple equation
  • Vectorize too slow in python? Or is it quad.integrate? Or is it my code?
  • Can you put a += operator into a list comprehension?
  • ValueError: cannot copy sequence with size 5 to array axis with dimension 3 in Numpy
  • In Python, iteration doesn't work as I intended
  • Python program to read a excel sheet does not work?
  • How can i append values to an existing key in a dictionary in python? in a loop without " "
  • sorting list numerically based from column from file
  • How does inplace add work in tuples if tuples do not include __iadd__ but still use INPLACE_ADD instruction?
  • random_randint does not work with merge sort
  • Better way to print a grid without using a for loop in python
  • Mutable and immutable objects in python
  • Dataframe to slice column content by searching sub-string
  • Concatenation from multiple row in a new column Python Pandas
  • How to connect python project to my HTML CSS website
  • How to merge two lists horizontally
  • Hex string to floating point conversion in python mismatching with IEEE-754 value
  • Python: Removing an item from a list based on input()?
  • Prevent f string from converting float into scientific notation
  • Popping a key from dict() safely and in the most idiomatic way if a.) key doesn't exist or b.) key is not validated
  • How to Select and click button to login to web page?
  • len(string) is showing more index numbers than the actual string
  • Are there differences between string.replace / .strip / .find and the built-in functions?
  • Categorize the repetitive values in a column using pandas
  • forward slash in string literal behaves unexpectedly
  • Why are my python nested if statements not working?
  • How can I add the attributes of 2 classes using method overloading?
  • What can cause a “Resource temporarily unavailable” on sock connect() command
  • Python - Fast way to sample data from array when sample size changes
  • The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number be
  • Combine current element with next element in a list
  • Split all Data in a Column in Pandas (Python)
  • Is python 3 semantically versioned and forwards compatible
  • Allow failure for all tests if specific Error is thrown
  • Creating one nested list from separate lists
  • Efficient enemy avoidance for pathfinding with fewer enemies
  • How do I add more variables to class if I don't know how many I would add (python)
  • How to use return values from two functions to make an if statement and break process
  • How to change the places of numbers in list, python
  • How to populate a pandas dataframe (dfA) column "A" with values from another dataframe (dfB), depending on col
  • How to remove duplicates from list in python
  • Python Pandas XLRDError when reading .xls files
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org