Questions tagged [group-by]

GROUP BY is a command in the SQL relational database standard, and pandas, for collapsing a group of rows that share common field value(s) into a single row. Aggregate functions can be performed on other fields in the group, such as SUM() or AVG(), to collate related data into a single value.

Filter by
Sorted by
Tagged with
1 vote
1 answer
25 views

Inserting and updating records at the same time

create table test ( id serial, contract varchar, amount int, aggregated int, is_aggregate int ); insert into test (contract, amount, aggregated) values ('abc', 100, 0), ...
Westcoaster's user avatar
0 votes
0 answers
7 views

Grouper and axis must be of same length

I want to group a data according to day and month but the error shows "grouper and axis must be same length. what can I do? df2['Date'] = df2['Date'].astype(str) times1= pd.DatetimeIndex(df2['...
Aryan Jain's user avatar
1 vote
1 answer
27 views

How do I groupby multiple columns in a pandas dataframe?

I'm working board game data from BoardGameGeek, and I'd like to create a dataframe that groups board games by the minimum number of players AND by categories. Here are the column names: ['name', '...
itsanhtuanho's user avatar
0 votes
0 answers
34 views

Counting unread messages or annoucements for a given user [duplicate]

I'm working on a simple internal messaging/annoucement system to use on a company portal/website. I would like to get the count of unread messages or annoucements for a given user. Because the ...
Bruce AaLee's user avatar
0 votes
1 answer
19 views

split excel sheet in python pandas without loosing source formatting

I'm trying to split an excel file in pycharm by importing pandas. My code is splitting the sheet based on key value and properly copying the text in the target. But the source file format is not being ...
Ramakrishna G's user avatar
0 votes
1 answer
7 views

MySQL Getting filtered row from one table based on a value in another table

I am having an issue joining these two tables. The query below will return ID-A 1 and 8. However, I also want to check if ID-A has StatusCode= 2 in TableA. How do I join the two tables that return ...
Allen King's user avatar
  • 2,374
-1 votes
0 answers
35 views

Get percent of column value count compared to same column value count in another table during certain time period grouping by column value

Looking for share of each Agent's rows where task = 'Stalking' in table Stalking compared to occurrences in table Assigned during Min and Max stalkDate in table Stalking. Table Assigned Agent task ...
Kaptah's user avatar
  • 9,783
0 votes
1 answer
38 views

Group rows when one column's number value is between or following two other columns values

I have the flowing problem. I have a data frame as follow: Country_code country low_range high_range ----------------------------------------------------- AU Australia 1 ...
Arsenfat's user avatar
0 votes
0 answers
34 views

How to populate the amount received for each id based on the outstanding amount in given months

Below is the typical example of the dataset where I have Unique ID, Date and OS. OS is the outstanding loan amount at a particular month and the X1 (Out)~ X10(Out) is the output to be calculated for ...
Asit's user avatar
  • 9
0 votes
1 answer
17 views

Is there a way in python using Pandas to merge two rows when one column value is equal the another column value of the following line

I have the flowing problem. I have a data frame as follow: Country_code country low_number high_number ----------------------------------------------------- AU Australia 1 ...
Arsenfat's user avatar
0 votes
0 answers
20 views

Does the order of inf and not-inf matter in pandas.groupby.agg(sum) function?

I tried to calculate the sum of a grouped pd.DataFrame (or pd.Series) containing inf. Thereby, I figured out that the location of the inf in the original pd.DataFrame will influence the result beeing ...
gtd88's user avatar
  • 1
0 votes
2 answers
18 views

aggregate function with Window functions vs aggregate function with Group By [closed]

Can anyone explain me the actual difference between the window functions and Group by, like how the things work internally when we try to do sum using window functions and group by. Which one works ...
Likhith Chakravarthi K C's user avatar
3 votes
2 answers
43 views

Obtaining grouped max() or min() in Pandas without skipping NANs

Consider a sample dateframe df = pd.DataFrame({'group' : [1, 2, 2], 'x' : [1, 2, 3], 'y' : [2, 3, np.nan]}) If I want to get the max value of variable 'y' without skipping NANs, I would use the ...
PingPong's user avatar
  • 407
1 vote
1 answer
43 views

What is the best way to find frequency of data receival?

I'm trying to determine reporting period from a dataframe of reports. Options for reporting period would be: Monthly Quarterly Other The dataframe looks like this: data = [['F000003Y6H', '2018-07-31'...
shwe11's user avatar
  • 13
0 votes
2 answers
36 views

Create ranges with CASE statemant - ERROR: Each GROUP BY expression must contain at least one column that is not an outer reference

I'm tring to create ranges using CASE but I have a problem with counting the numbers of appearances. At the moment my code looks like this: SELECT CASE WHEN engine_capacity < 1 THEN 'less than ...
RageAnalyst's user avatar
2 votes
2 answers
42 views

Select common rows across different years

I have a very large dataframe containing 150,000 rows and 1,000 ID values, across 20 years. I want to keep all the rows that have common ID value across different years. x <- structure(list(ID = c(...
user27808's user avatar
  • 121
1 vote
2 answers
65 views

Groupby using a sequence and computing sum

I've a dataframe like this, Name COST Timestamp 0 c 8 2023-09-20 15:14:46 1 a 8 2023-09-20 15:14:48 2 c 9 2023-09-20 15:14:55 3 b 10 2023-09-20 15:15:00 4 c 4 2023-...
Starlord22's user avatar
0 votes
3 answers
49 views

For each value, find the smallest distance within the group using Pandas

suppose I have the following data frame df group value a 1 a 0 a 3 b 1 b 4 For each value, I want to find the closest value in the same group ('a' or 'b'),and then ...
Wendy's user avatar
  • 13
1 vote
1 answer
25 views

Calculate percentage change by year and sector in Julia

I have dataframe as follow: julia> println(df_roa_kvkt) 15×3 DataFrame Row │ year sector roa │ Int64 String Float64 ─────┼────────────────────────────...
Tann's user avatar
  • 23
1 vote
1 answer
25 views

Aggregate dynamically a list of dynamically created columns in PySpark

I have added a list (over 100) of columns to a dataframe dynamically. The columns with negative numbers are those columns which were generated from the value of the bookID column. In each row, only ...
Mojdeh Ebrahimi's user avatar
0 votes
1 answer
25 views

Python: group by one object attribute

I have a generator containing 5400 Sqlalchemy rows of 1 table(Entity). I would like to group rows by the value of one column (let's say column 1); for each "group" I want to calculate the ...
NicWorkAccount's user avatar
0 votes
0 answers
22 views

Looping over two character/string columns (variables) that behave like factor-level variables

I have a large panel dataset with mostly character variables, and I would like to loop through one of these (let's call it A, perhaps via a list?) so that I can create different datasets/dataframes ...
Saul Alamilla's user avatar
1 vote
2 answers
44 views

How to calculate Retention rate of Userplayed?

I have database of UserPlayed of a mobile game containing these: df = pd.DataFrame({ 'AppVersion':['1.0.20','1.0.20','1.0.20','1.0.20','1.0.20','1.0.20','1.0.22','1.0.22','1.0.22','1.0.22'], '...
Danny Nguyen's user avatar
0 votes
0 answers
14 views

group by and create extra column of dummies in pandas [duplicate]

I have: df = pd.DataFrame({'col1':['a','b','c','a'], 'col3':['A','A','B','D']}) df I want to group by column1, and create extra columns showing the column 3 values, and a ...
frank's user avatar
  • 3,048
0 votes
2 answers
30 views

Group By function not doing GROUP BY using WITH CTE Statement in Oracle

I have a procedure which is mostly used to GROUP BY data and present in a single line. But with the below code, I am able to see same SPANID multiple times. Image below for reference. Also below is ...
Nad's user avatar
  • 4,618
1 vote
1 answer
35 views

Looking to reindex dates based on a groupby of Grid Cell

I am attempting to do something similar to the reindexing in Pandas reindex date index by group revisited except I have one extra level of indexing involved. My data is in the following structure: [...
arctic_climate_science's user avatar
0 votes
1 answer
120 views

How to calculate the number of times the same values occur in one column and another values occur in another column?

So this is my sample dataframe. 'CUSTOMER_ID': [31381, 7180, 132, 334, 11, 78], 'TX_DATE': ['2023-06-01', '2024-03-08', '2023-03-07', '2003-03-01', '2020-03-02', '2023-03-08'], 'TX_WEEK': ...
sarhh's user avatar
  • 3
-1 votes
1 answer
39 views

pandas groupby middle heading

How to group this data with pandas by heading in column sl. no I have data like below in CSV or excel. sl. No v1 v2 v3 Heading1 1 243 45 3244 2 3 25 33 3 43 324 54 Head2 1 3 45 54 2 24 4 42 .....
Hillal Kumar Roy's user avatar
0 votes
1 answer
12 views

For each group, count the number of dates that occur before each date in other list

Date1 Group 2023-05-17 1 2023-06-23 2 Date2 <- c("2023-05-31", "2023-06-30", "2023-07-31") So for each Group, I would like to count the total number of Date1 that ...
biostat_help's user avatar
0 votes
1 answer
15 views

Getting a "Caused by error in `UseMethod()" when using Count function after Group_by

I am trying to create an equal weight column within my dataframe, by dividing 100 by the number of records per unique date (marketdate). I used Group_by(marketdate) and then used a Count function, but ...
Richard's user avatar
0 votes
1 answer
40 views

Laravel: GroupBy and orderBy not working together

I'm trying to select all attachments of a person and group by a field but if I add orderBy clause to show only last document of that category it doesn't work. It always use first id to group. Using -&...
Loris's user avatar
  • 1
2 votes
3 answers
86 views

Python Polars: Calculate time difference from first element in each (repeating) group

I have a polars.DataFrame like: df = pl.DataFrame({ "timestamp": ['2009-04-18 11:30:00', '2009-04-18 11:40:00', '2009-04-18 11:50:00', '2009-04-18 12:00:00', '2009-04-18 12:10:00', '2009-04-...
OliverHennhoefer's user avatar
0 votes
4 answers
62 views

How to group array entries by key and by key value in jq?

Given this json: { "hits": [ { "country": "PT", "level": "H2", "id": "id1" }, { "...
António's user avatar
0 votes
1 answer
36 views

Grouping of Sub-Tables while Maintaining Ranges of Time

I'm working with a table that maintains a history of records for each key, alongside a START_DATE and END_DATE field that signifies when the record changes go in and out of action, respectively: KEY ...
braedynl's user avatar
0 votes
2 answers
39 views

Pandas: re-assign values for groups to same value in one column if they have at least one common in another

I have following dataframe: df = pd.DataFrame({"zip":['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A','C', 'C', 'C','C', 'C', 'C'], "zip_splitted":['...
Alex_Y's user avatar
  • 590
1 vote
1 answer
26 views

Get record where a value is unique in the whole table/column

I am looking to get the row where a value is unique in the whole column: col1 col2 col3 value 1 value 2 value 3 value 1 value 2 value 3 value a value b value c value a value x value c value 1 ...
tiberiusz's user avatar
0 votes
1 answer
38 views

SQL group by multiple columns with seperate where statements and left join

I want to select all delivery stops for a driver. If 2 orders have the same delivery_id location it should only be one stop. Similarly if the pickup_id and delivery_id of different orders are the same ...
Junior Nicolle's user avatar
0 votes
2 answers
48 views

Pandas groupby to create additional columns from one column

I have a dataframe that contains a date column and a discount value column, as follows: import pandas as pd import numpy as np df = pd.DataFrame({'date': ['2023-09-01', '2023-09-02', '2023-09-03', '...
jimiclapton's user avatar
0 votes
1 answer
33 views

Change different row data into columns

I am a beginner in Pandas and I have been struggling with this problem for several days now. I am using pandas, plotly and streamlit in order to create more customized charts Below is the table I have ...
danielmf93's user avatar
1 vote
0 answers
19 views

pandas drop column based on condition on groupby

I have a data like this: I want to group by "Stok Kodu" column and sort by "Miktar" column then create table to another excel file. When i use this code; df = df.groupby(["...
barbudos's user avatar
-1 votes
2 answers
50 views

Getting error on selecting those columns also which are not used to create group while using using group by?

I am using PostgreSQL If I want to get customer.first_name, customer.last_name or any other column in addition to customer_id and sum(total), I am getting error as shown below: select i.customer_id, ...
Ruchi Raina's user avatar
-1 votes
1 answer
34 views

pandas group by with multiple agg not working on multiple columns

file table need to be I have a dataset where I need to report same exact image. Sub-activity is int project is a category " 3 project only" status is block, complete, on going is that doable ...
Sultan's user avatar
  • 5
-1 votes
1 answer
49 views

Want to select multiple Columns but group By only 1 Column

I having total 4 columns in Select query. Year, Net Value, Development Cost & Maintenance Cost. From these 4 columns Net Value & Development Cost is calculated using SUM() method but ...
Sumeet Kumar's user avatar
2 votes
1 answer
32 views

How to group by similar datetime?

I'm trying to group together transactions that are between a period of one hour... so I'm not getting anything. follow the example below structure(list(`data hora` = c("01/10/2023 01:00", &...
viniciuscaldeira's user avatar
0 votes
1 answer
34 views

Renaming a Pandas Dataframe column and Groupby

student_data.rename(columns={"date_Of_Birth":"dob"}, inplace=True) student_data.head() I have tried it with both with and without inplace but still it is not working. And another ...
Amit Sur's user avatar
1 vote
1 answer
29 views

Adding 1 more column to grouped by dataframe [duplicate]

I currently have these 2 dataframes(before/after) Before: timestamp cnt t1 t2 hum wind_speed is_holiday weather year month day 0 2015-01-04 00:00:00 182 3.0 2.0 93.0 6.0 0 broken ...
krmbla's user avatar
  • 51
-1 votes
2 answers
27 views

MySQL MIN/MAX Select based on different criteria in a single select statement

In mySQL, have a large table of history data and I am looking for an elegant way to be able to select the earliest/latest event types in a single select statement without grouping by Item and Event ...
CJRV's user avatar
  • 23
0 votes
0 answers
18 views

How to plot certain row values from multiple dataframes? [duplicate]

I have 10 dfs with same column names. They look like the following: country_code country x y SVN Slovenia 29.794 21.041 ESP Spain 380.429 ...
strawhat's user avatar
2 votes
2 answers
42 views

Calculate time duration while iterating on the same column

Would it be possibile to calculate the daily sum of hours based on the difference between time present in same colums? date time 2017-11-08 08:25:57 2017-11-08 12:31:59 2017-11-08 13:28:42 2017-...
user2239318's user avatar
  • 2,610
0 votes
1 answer
44 views

How to use a field value for IN() condition?

I have following structures: CREATE TABLE `proxies` ( `proxy_id` int(11) NOT NULL AUTO_INCREMENT, `proxy_ip` varchar(50) DEFAULT NULL, `proxy_port` smallint(5) unsigned DEFAULT NULL, `...
Behzad Safamanesh's user avatar

1
2 3 4 5
552