萌︼了一个春

文章 评论 浏览 32

萌︼了一个春 2025-02-17 11:55:20

您需要将第二行更改为

let columnFromBackend = await getData();

您正在使用哪个版本的节点?

You need to change your second to last line to

let columnFromBackend = await getData();

Which version of node are you using?

从django-rest-api中获取with react Frontend的JSON数据成变量

萌︼了一个春 2025-02-17 03:21:48

@Jeff Scott Brown 已经正确解释了Groovy封闭方式。我要在此解释SPOCK测试DSL细节,因为他似乎对它们不了解:

1 * object.statusrepository.save(...)意味着要验证<<<代码>保存方法是按照参数约束(...)中指定的一个指定的一次调用。您想阅读有关 1 *。

{
    it.Id == request.Id
    it.location == location
    it.team == statusExisting.getTeam()
    it.statusEnum == StatusEnum.Status.W
}

方法参数,指定参数需要遵守正匹配的条件。

四行代码称为条件。它们是用于断言的句法或速记,也是Spock DSL的基本构件之一。它们是使写作和阅读Spock测试进行优雅,表现力和直观的一部分。

我强烈建议您学习一些基本的Groovy语法,并阅读SPOCK手册。堆栈溢出并不是您跳过使用新工具或新语言的学习部分的快捷方式。

这是一个简化的 mcve 您情况的版本:

class Data {
    def Id
    def location
}
class Subject {
    def save(Data data) {}

    def doSomething() {
        save(new Data(Id: 1234, location: 'somewhere'))
    }
}
class MySpec extends Specification {
    def test() {
        given:
        Subject subject = Spy()

        when:
        subject.doSomething()

        then:
        1 * subject.save({
            it.Id == 1234
            it.location == 'somewhere'
        })
    }
}

Groovy Web Console.

只需在数据构造函数调用或参数约束条件中更改一个值,以查看测试失败即可。

@Jeff Scott Brown already correctly explained how Groovy closures work. I am going to explain the Spock testing DSL specifics on top of that, because he does not seem to know about them:

1 * subject.statusRepository.save(...) means to verify that the save method is called exactly once as specified inside the argument constraint (...). You want to read about cardinality in Spock in order to understand 1 *.

{
    it.Id == request.Id
    it.location == location
    it.team == statusExisting.getTeam()
    it.statusEnum == StatusEnum.Status.W
}

is an argument constraint for the first method argument, specifying conditions that argument needs to comply with for a positive match.

The four lines of code are called conditions. They are syntactic sugar or shorthands for assertions and one of the basic building blocks of the Spock DSL. They are part of what makes writing and reading Spock tests to elegant, expressive and intuitive.

I strongly recommend you to learn some basic Groovy syntax and also read the Spock manual. Stack Overflow is not meant to be your shortcut for skipping the learning part of using a new tool or a new language.

Here is a simplified MCVE version of your situation:

class Data {
    def Id
    def location
}
class Subject {
    def save(Data data) {}

    def doSomething() {
        save(new Data(Id: 1234, location: 'somewhere'))
    }
}
class MySpec extends Specification {
    def test() {
        given:
        Subject subject = Spy()

        when:
        subject.doSomething()

        then:
        1 * subject.save({
            it.Id == 1234
            it.location == 'somewhere'
        })
    }
}

Try it in the Groovy Web Console.

Just change a value in the Data constructor call or in the argument constraint condition in order to see the test fail.

Groovy语法和可变?

萌︼了一个春 2025-02-16 11:39:58

尽管没有合适的图表类型,但您可以创建仪表并将其作为图像插入。

Although there is no suitable Chart type, you can create a gauge and insert it in the report as an image.

C#Winforms报告图表(DEVEXPRESS)

萌︼了一个春 2025-02-16 05:08:27

您只需添加多个 .with 语句,而 knex 将为您整理。

我相信您的查询最终会这样看:

const query = knex
    .with(
      'first',
      knex('results')
        .select(
          'results.simulation_id',
          'simulation_time',
          'variable',
          'value',
          'runset_id',
          knex.raw(`(case WHEN ended_at is null then 'INCOMPLETE' else 'COMPLETE' END) as status`),
        )
        .join('bookkeeping as bk', 'bk.simulation_id', 'results.simulation_id')
        .where('bk.simulation_id', 1)
        .andWhere('variable', INSERT_VARIABLE_HERE)
        .orderBy('simulation_time'),
    )
    .with(
      'second',
      knex('bookkeeping')
        .select(
          'simulation_id',
          db.raw('null::real as simulation_time'),
          db.raw('null as variable'),
          db.raw('null::real as value'),
          db.raw('null as runset_id'),
          db.raw(`(case WHEN ended_at is null then 'INCOMPLETE' else 'COMPLETE' END) as status`),
        )
        .whereNotExists(knex('first'))
        .andWhere('simulation_id', INSERT_VARIABLE_HERE),
    )
    .select('*')
    .from('first')
    .unionAll([knex('second').select('*')]);
};

You can just add multiple .with statements and knex will sort it out for you.

I believe your query would end up looking this like this:

const query = knex
    .with(
      'first',
      knex('results')
        .select(
          'results.simulation_id',
          'simulation_time',
          'variable',
          'value',
          'runset_id',
          knex.raw(`(case WHEN ended_at is null then 'INCOMPLETE' else 'COMPLETE' END) as status`),
        )
        .join('bookkeeping as bk', 'bk.simulation_id', 'results.simulation_id')
        .where('bk.simulation_id', 1)
        .andWhere('variable', INSERT_VARIABLE_HERE)
        .orderBy('simulation_time'),
    )
    .with(
      'second',
      knex('bookkeeping')
        .select(
          'simulation_id',
          db.raw('null::real as simulation_time'),
          db.raw('null as variable'),
          db.raw('null::real as value'),
          db.raw('null as runset_id'),
          db.raw(`(case WHEN ended_at is null then 'INCOMPLETE' else 'COMPLETE' END) as status`),
        )
        .whereNotExists(knex('first'))
        .andWhere('simulation_id', INSERT_VARIABLE_HERE),
    )
    .select('*')
    .from('first')
    .unionAll([knex('second').select('*')]);
};

knexjs-多个`with'with'with unional

萌︼了一个春 2025-02-15 17:57:30

推动在这里没有意义。 push 意味着您有一个要添加值的数组。但是在这里您只想初始化一个数组,因此您必须使用另一种方法。

(同样值得注意的是,如果您在雄辩模型上使用 push ,它也将其保存到数据库),

您可以执行诸如 $ $ product-&gt; image ['productc'] = []之类的事情。

,然后 $ product-&gt; save()如果要保存

Push doesn't make sense here. push implies that you have an array that you want to add a value to. But here you just want to initialise an array, so you'll have to use another method.

(Also notably if you use push on an eloquent model it'll also save it to the database)

You could do something like $product->image['productC'] = []

And then $product->save() if you want to save it

使用`push'在laravel中创建一个字段数组

萌︼了一个春 2025-02-15 12:54:53

关键信息在有用的评论中, santiago squarzon Mathias R. Jessen ,但让我将其分解为概念上

稍后会很清楚,您的 iSvalidn function 在语句中在语句中调用,但不会产生 display 输出。

  • powershell函数和脚本没有返回值 - 它们产生 output ,通常写入成功输出流< /em>,PowerShell的类似于 stdout (标准输出)。

    • 从这个意义上讲,PowerShell的功能更像是传统的 shell 而不是典型的编程语言。

    • 与传统外壳不同,PowerShell提供输出流,而定位这些流是一种输出信息的方式, 调试消息。存在专用的cmdlet来针对每条流,如概念 about_output_streams 帮助主题。




  • 函数或脚本中的任何语句如果来自命令调用的输出或表达式的值没有捕获或重定向,或者很少有必要 - 写入输出 cmdlet, echo 是一个内置的别名。

    • 这意味着任何脚本或函数都可以具有开放式数字(多个)“返回值”。

    • 相比之下, 旨在将信息打印到 host (显示,终端)和旁路成功输出流(由于PowerShell的版本5,它写入信息流,这些信息流(如所有流所做的)默认为主机)。因此,有时将其用作提供调试输出的快速方法,尽管通常最好使用 写入debug (仅用于调试)或



  • 与其他语言不同,返回不是输出数据所需的 - 除非需要退出范围,否则它的使用可选 - 可以独立于输出语句使用;如句法糖,输出的数据可以传递给 return ;例如,返回0 -LT 1 对于以下两个单独的语句 0 -LT 1;返回 0 -LT 1 输出 -LT 操作的值,返回然后退出范围。



将上述应用于您尝试的

function isValidN {
      echo "isValidN is called"
      return 0 -lt 1
    }

是否等效:

function isValidN {
      Write-Output "isValidN is called"
      Write-Output (0 -lt 1)
      return
    }

或,使用 intimit 输出,并省略冗余 return 呼叫,鉴于范围隐含在函数末尾退出:

function isValidN {
      "isValidN is called"
      0 -lt 1
    }

因此,您的函数输出两个对象:字符串“ Isvalidn称为” ,以及 0 -LT的评估1 ,是 $ true

使用命令调用(包括脚本和函数)中该命令,使得:

if (isValidN) # ...

有效地变为:

if (@("isValidN is called", $true)) # ...

也就是说,函数 iSvalidn 的两个对象输出(捕获)变成两元素 array (类型 [object []] ),由于它与(如果)一起使用,它被隐式评估为布尔值( [boo] )。

PowerShell允许任何要转换为 [bool] 的对象和2+ - 元素阵列始终评估 $ $ true ,无论其内容如何 - 请参见此答案有关PowerShell的to -Boolean转换规则的摘要。

总结:

  • 您打印到 display “ Isvalidn”被称为“ ,成为该函数输出的一部分(”返回值”),“污染”该函数的输出使用偶然数据,如果有条件评估为 $ true 始终。。

  • 因为“ Isvalidn被称为“ 是输出的一部分,并且该输出被捕获的(并被)(如果),如果有条件,它从未打印到显示器上。


我认为 you 的意思是

function isValidN {
      Write-Debug 'isValidN is called'
      0 -lt 1
    }

# Make Write-Debug output visible.
# To turn it back off:
#   $DebugPreference = 'SilentlyContinue'
$DebugPreference = 'Continue'

# Call the function
if (isValidN) { 't' } else { 'f' }

输出:

DEBUG: isValidN is called
t

注意:

The crucial information is in the helpful comments by Santiago Squarzon and Mathias R. Jessen, but let me break it down conceptually:

As will become clear later, your isValidN function was called in the if statement, but produced no display output.

  • PowerShell functions and scripts do not have return values - they produce output that is typically written to the success output stream, PowerShell's analog to stdout (standard output).

    • In that sense, PowerShell functions more like a traditional shell rather than a typical programming language.

    • Unlike traditional shells, however, PowerShell offers six output streams, and targeting these streams is a way to output information that isn't data, such as debugging messages. Dedicated cmdlets exist to target each streams, as detailed in the conceptual about_Output_Streams help topic.

  • Any statement in a function or script may produce output - either implicitly, if output from a command call or the value of an expression isn't captured or redirected, or explicitly, with the - rarely necessary - Write-Output cmdlet, for which echo is a built-in alias.

    • The implication is that any script or function can have an open-ended number (multiple) "return values".

    • By contrast, Write-Host is meant for printing information to the host (display, terminal), and bypasses the success output stream (since version 5 of PowerShell, it writes to the information stream, which - as all streams do - goes to the host by default). As such, it is sometimes used as a quick way to provide debugging output, though it's generally preferable to use Write-Debug (for debugging only) or Write-Verbose (to provide extended information to the user on demand), but note that making their output visible requires opt-in.

  • Unlike in other languages, return is not needed to output data - unless there is a need to exit the scope at that point, its use is optional - and may be used independently of output statements; as syntactic sugar, data to output may be passed to return; e.g., return 0 -lt 1 is short for the following two separate statements 0 -lt 1; return: 0 -lt 1 outputs the value of the -lt operation, and return then exits the scope.


Applying the above to what you tried:

function isValidN {
      echo "isValidN is called"
      return 0 -lt 1
    }

is the equivalent of:

function isValidN {
      Write-Output "isValidN is called"
      Write-Output (0 -lt 1)
      return
    }

Or, using implicit output, and omitting the redundant return call, given that the scope is implicitly exited at the end of the function:

function isValidN {
      "isValidN is called"
      0 -lt 1
    }

Thus, your function outputs two objects: String "isValidN is called", and the evaluation of 0 -lt 1, which is $true

Using a command call (including scripts and functions) in an if conditional - captures all output from that command, so that:

if (isValidN) # ...

effectively becomes:

if (@("isValidN is called", $true)) # ...

That is, the two-object output from function isValidN, when captured, turned into a two-element array (of type [object[]]), which was implicitly evaluated as a Boolean ([bool]) due to its use with if.

PowerShell allows any object to be converted to [bool], and a 2+-element array always evaluates to $true, irrespective of its content - see the bottom section of this answer for a summary of PowerShell's to-Boolean conversion rules.

To summarize:

  • What you meant to print to the display, "isValidN is called", became part of the function's output ("return value"), "polluting" the function's output with incidental data, making the if conditional evaluate to $true always.

  • Because "isValidN is called" was part of the output, and that output was captured (and consumed) by the if conditional, it never printed to the display.


What I assume you meant do to:

function isValidN {
      Write-Debug 'isValidN is called'
      0 -lt 1
    }

# Make Write-Debug output visible.
# To turn it back off:
#   $DebugPreference = 'SilentlyContinue'
$DebugPreference = 'Continue'

# Call the function
if (isValidN) { 't' } else { 'f' }

Output:

DEBUG: isValidN is called
t

Note:

powershell逻辑函数在从if语句中调用时不会执行

萌︼了一个春 2025-02-15 04:19:48

// var dateTime = message.getDate();
var dateTime = utilities.formatdate(message.getDate(),时区,“ dd-mm-yyyy”);

尝试一下

// var dateTime = message.getDate();
var dateTime = Utilities.formatDate(message.getDate(), timezone, "dd-MM-yyyy");

try this

提取电子邮件日期问题 - Google脚本

萌︼了一个春 2025-02-14 11:05:49

遇到您的问题以搜索其他问题,但是您可能会尝试以下内容(当您编写问题时,这可能是不可用的):

在Mac的Docker中,转到设置 - &GT;开发功能,并启用“使用Rosetta ...”设置。

设置Dev-containers(我需要Linux images的另一个用例)时,这对我有用

Ran into your question searching for something else, but you might try the following (this was probably not available when you wrote your question):

In docker for Mac, go to Settings --> Features in development, and enable 'Use Rosetta ...' setting.

enter image description here

This worked for me when setting up dev-containers (another use-case where I needed Linux images)

如何在基于手臂的Mac上运行CENOS7 Docker图像

萌︼了一个春 2025-02-14 09:08:59

我只能获得联系人,所有者,创建和更新的ID
字段。用于获取相应名称的哪个API?

谢谢 @ sindhuja laxmipuram 在此处发布您的建议,作为社区Wiki,对其他社区成员有益于类似的问题

您可以使用以下命令列出的联系人或所有者名称
上述

 获取{endpoint}/catalog/api/atlas/v2/entity/guid/guid}?minextinfo = {minextinfo}
 

有关更多信息,请参阅此,因此线程 | <强>如何使用REST API从Azure Purview帐户中提取角色分配信息

i am only getting the Ids of contacts, owners, createdby and updatedby
fields. Which API to use to get the corresponding names?

Thank you @Sindhuja Laxmipuram posting your suggestion here as community wiki to beneficial for other community members for similar issue.

You can use the below command to list the contact or owner name for
the above.

 GET {Endpoint}/catalog/api/atlas/v2/entity/guid/{guid}?minExtInfo={minExtInfo}&ignoreRelationships={ignoreRelationships}

For more information please refer this SO THREAD | How to use REST API to extract role assignment information from a Azure Purview account .

purview API显示联系人名称

萌︼了一个春 2025-02-14 01:37:50

我认为它是一个C代码。您提供的代码中似乎存在多个错误。

首先,您不会意识到父母的成功阅读文件是因为:

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc failed to read file\n");

应该是

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc ok to read file\n");

,也许以下是:

int fd = open("myDir/myFile.txt", O_CREATE|O_RDWR);
wrte(fd, "123\n",4);

int fd = open("myDir/myFile.txt", O_CREAT|O_RDWR);
write(fd, "123\n",4);

添加:

如果您在叉子前解开安装命名空间,则您会期望父母和孩子属于同一安装命名空间。

也许您应该在其他地方移动“ unshare(mount_ns)”:

int pid = fork()
if (pid ==0) {
  unshare (mount_ns)
  makedir("myDir");
  ...

最好的问候。

I assume its a C code. There seems to be multiple mistakes in the code that you provided.

First of all, you would not realize that parent success to read the file because:

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc failed to read file\n");

should be

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc ok to read file\n");

Moreover, maybe the following:

int fd = open("myDir/myFile.txt", O_CREATE|O_RDWR);
wrte(fd, "123\n",4);

should be:

int fd = open("myDir/myFile.txt", O_CREAT|O_RDWR);
write(fd, "123\n",4);

Additionnally:

If you unshare your mount namespace BEFORE the fork, you will expect both parent and child belonging to the same mount namespace.

Maybe you should move the 'unshare (mount_ns)' somewhere else like this:

int pid = fork()
if (pid ==0) {
  unshare (mount_ns)
  makedir("myDir");
  ...

Best regards.

解开坐骑命名空间后文件访问

萌︼了一个春 2025-02-14 00:36:39

将MiterateApp移动到主要方法内部

move MaterialApp to inside of main method

NavigationPush不像应该做的那样在颤音中工作

萌︼了一个春 2025-02-13 04:53:25

不确定这是否适合您的测试,但是您可以将导航与 cy.intercept()固执。

const href = 'url-from-link-href'

cy.location().then(loc => {  

  cy.intercept({url: href}, (req => {
    expect(req.url).to.eq(href)  // confirms href seen on intercepted network call
    req.url = loc.href           // stop navigation, remain at original loc
  })).as('redirect')

  cy.get(`a[href="${href}"]`)
    .click()                     // click the link
  cy.wait('@redirect')           // confirms intercept caught the redirect

  cy.visit(href)
  ... 
})

Not sure if this will suit your test, but you can stub the navigation with cy.intercept().

const href = 'url-from-link-href'

cy.location().then(loc => {  

  cy.intercept({url: href}, (req => {
    expect(req.url).to.eq(href)  // confirms href seen on intercepted network call
    req.url = loc.href           // stop navigation, remain at original loc
  })).as('redirect')

  cy.get(`a[href="${href}"]`)
    .click()                     // click the link
  cy.wait('@redirect')           // confirms intercept caught the redirect

  cy.visit(href)
  ... 
})

柏树从iframe退出后失去了测试方案

萌︼了一个春 2025-02-12 20:58:37

解决方案很简单。就像可以使用 setenv 打印的环境一样,您可以使用 set 打印本地变量。希望它有用!

The solution is quite simple. Just like the environment wich can be printed with setenv, you can print the local variables with set. Hope it was useful !

在外壳中打印所有本地变量

萌︼了一个春 2025-02-12 19:08:13

只需将逻辑更改为字符就会有所帮助。

dat%>%
  mutate(across(is.logical, ~as.character(.x))) %>%
  tidyr::pivot_longer(!c(id,month), names_to = "check_spot", values_to = c("control_check"))

   id    month check_spot control_check
   <chr> <dbl> <chr>      <chr>        
 1 A         1 C1         TRUE         
 2 A         1 C2         FALSE        
 3 A         1 C3         ok           
 4 A         2 C1         FALSE        
 5 A         2 C2         FALSE        
 6 A         2 C3         not          
 7 A         3 C1         FALSE        
 8 A         3 C2         TRUE         
 9 A         3 C3         wanrning     
10 B         1 C1         TRUE         
11 B         1 C2         TRUE         
12 B         1 C3         not          
13 B         2 C1         FALSE        
14 B         2 C2         FALSE        
15 B         2 C3         not          
16 B         3 C1         TRUE         
17 B         3 C2         FALSE        
18 B         3 C3         ok    

重新排序?

dat%>%
  mutate(across(is.logical, ~as.character(.x))) %>%
  tidyr::pivot_longer(!c(id,month), names_to = "check_spot", values_to = c("control_check")) %>%
  arrange(id, check_spot)

   id    month check_spot control_check
   <chr> <dbl> <chr>      <chr>        
 1 A         1 C1         TRUE         
 2 A         2 C1         FALSE        
 3 A         3 C1         FALSE        
 4 A         1 C2         FALSE        
 5 A         2 C2         FALSE        
 6 A         3 C2         TRUE         
 7 A         1 C3         ok           
 8 A         2 C3         not          
 9 A         3 C3         wanrning     
10 B         1 C1         TRUE         
11 B         2 C1         FALSE        
12 B         3 C1         TRUE         
13 B         1 C2         TRUE         
14 B         2 C2         FALSE        
15 B         3 C2         FALSE        
16 B         1 C3         not          
17 B         2 C3         not          
18 B         3 C3         ok     

Just change logical to character will helps.

dat%>%
  mutate(across(is.logical, ~as.character(.x))) %>%
  tidyr::pivot_longer(!c(id,month), names_to = "check_spot", values_to = c("control_check"))

   id    month check_spot control_check
   <chr> <dbl> <chr>      <chr>        
 1 A         1 C1         TRUE         
 2 A         1 C2         FALSE        
 3 A         1 C3         ok           
 4 A         2 C1         FALSE        
 5 A         2 C2         FALSE        
 6 A         2 C3         not          
 7 A         3 C1         FALSE        
 8 A         3 C2         TRUE         
 9 A         3 C3         wanrning     
10 B         1 C1         TRUE         
11 B         1 C2         TRUE         
12 B         1 C3         not          
13 B         2 C1         FALSE        
14 B         2 C2         FALSE        
15 B         2 C3         not          
16 B         3 C1         TRUE         
17 B         3 C2         FALSE        
18 B         3 C3         ok    

reorder?

dat%>%
  mutate(across(is.logical, ~as.character(.x))) %>%
  tidyr::pivot_longer(!c(id,month), names_to = "check_spot", values_to = c("control_check")) %>%
  arrange(id, check_spot)

   id    month check_spot control_check
   <chr> <dbl> <chr>      <chr>        
 1 A         1 C1         TRUE         
 2 A         2 C1         FALSE        
 3 A         3 C1         FALSE        
 4 A         1 C2         FALSE        
 5 A         2 C2         FALSE        
 6 A         3 C2         TRUE         
 7 A         1 C3         ok           
 8 A         2 C3         not          
 9 A         3 C3         wanrning     
10 B         1 C1         TRUE         
11 B         2 C1         FALSE        
12 B         3 C1         TRUE         
13 B         1 C2         TRUE         
14 B         2 C2         FALSE        
15 B         3 C2         FALSE        
16 B         1 C3         not          
17 B         2 C3         not          
18 B         3 C3         ok     

如何使用逻辑和字符列的DPLYR在R中旋转r长度?

萌︼了一个春 2025-02-11 21:55:30

有两种方法:1) groupby.apply np.average 和2)用懒惰的groupby手动计算。

路径1更容易编码,但是稍慢一点:

df.groupby('Date')\
  .apply(lambda x: np.average(x['QTY'], weights=x['Population']))\
  .reset_index(name='avg')

路径2更快,但更详细:

df['prods'] = df['QTY'] * df['Population']

groups = df.groupby('Date')

groups['prods'].sum().div(groups['Population'].sum()).reset_index(name='avg')

无论哪种方式,您都会给您输出:

         Date          avg
0  2021-01-01  8854.093023
1  2021-01-02  8841.767442

Note ,替代路径2的替代方案,而无需将新列添加到数据中,两次:

df['QTY'].mul(df['Population']).groupby(df['Date']).sum()\
   .div(df.groupby('Date')['Population'].sum())\
   .reset_index(name='avg')

涉及管道方法的另一种选择:

(df
.assign(weighted_qty = df.Population * df.QTY)
.groupby('Date')
.pipe(lambda df: df.weighted_qty.sum()/df.Population.sum())
)
Date
2021-01-01    8854.093023
2021-01-02    8841.767442
dtype: float64

There are two ways: 1) groupby.apply with np.average and 2) manually calculate with lazy groupby.

Path 1 is easier to code, but a little slower:

df.groupby('Date')\
  .apply(lambda x: np.average(x['QTY'], weights=x['Population']))\
  .reset_index(name='avg')

Path 2 is faster, but more verbose:

df['prods'] = df['QTY'] * df['Population']

groups = df.groupby('Date')

groups['prods'].sum().div(groups['Population'].sum()).reset_index(name='avg')

Either way gives you the output:

         Date          avg
0  2021-01-01  8854.093023
1  2021-01-02  8841.767442

Note, an alternative to Path 2 without adding new column to data involves groupby twice:

df['QTY'].mul(df['Population']).groupby(df['Date']).sum()\
   .div(df.groupby('Date')['Population'].sum())\
   .reset_index(name='avg')

Another option, involving the pipe method:

(df
.assign(weighted_qty = df.Population * df.QTY)
.groupby('Date')
.pipe(lambda df: df.weighted_qty.sum()/df.Population.sum())
)
Date
2021-01-01    8854.093023
2021-01-02    8841.767442
dtype: float64

如何创建每个日期数据集的加权平均值?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文