埖埖迣鎅

文章 评论 浏览 27

埖埖迣鎅 2025-02-13 12:44:41

使用数字格式渲染单元格值是Excel的函数。我认为Pandas和OpenPyXl只知道表的信息,例如值和数字格式,但不知道如何根据数字格式呈现单元格值。

如果愿意,我们可以根据数字格式将值渲染为字符串,就像Excel一样。我们可以通过OpenPyXl获取单元格的数字格式。

import openpyxl
workbook = openpyxl.load_workbook(excel_file)
sheet = workbook[workbook.sheetnames[0]]
print(sheet.cell(2,1).number_format)

Rendering cell value using number format is a function of Excel. I think pandas and openpyxl only know the information of the table, such as the value and number format, but do not know how to render cell value according to the number format.

If we wanted to, we can render the value as a string based on the number format, just like Excel. We can get the number format of the cell through openpyxl.

import openpyxl
workbook = openpyxl.load_workbook(excel_file)
sheet = workbook[workbook.sheetnames[0]]
print(sheet.cell(2,1).number_format)

使用read_excel()保留自定义数字格式,然后用pandas转换为csv

埖埖迣鎅 2025-02-13 12:00:43

我认为您要做的更像是共享的内存场景。如果您可以在开始goroutines的循环之后,就可以将其放在等待之后,那就更好了。
而且您应该使用互斥X来确保相互排斥。

而且我认为订单对这个问题无关。

I think what you are trying to do is more like a shared memory scenario. It would be better if instead of deferring the wait you can put it just after the loop that starts the goroutines.
And you should use a mutex to ensure mutual exclusion.

And I don't think order matters for this problem.

Golang中的平行算法到向量中的元素总和

埖埖迣鎅 2025-02-12 18:45:38

如果使用JavaScript,则可以使用[^] to 匹配包括newlines的任何字符

/s使用点来匹配任何字符也可行,但应用于整个模式,JavaScript不支持内联修饰符打开/关闭标志。

要匹配尽可能至少的字符,您可以通过附加问号来制作量词非贪婪,并使用a 捕获组提取两者之间的零件。

This is([^]*?)sentence

请参阅a regex101 demo

附带说明,要不匹配部分单词,您可以使用\ bthis句子\ b之类的单词边界

const s = "This is just\na simple sentence";
const regex = /This is([^]*?)sentence/;
const m = s.match(regex);

if (m) {
  console.log(m[1]);
}


JavaScript中的lougaround变体是(?< = this)[^]*?(?=句子),您可以检查 js正则表达式中的lookbehind 以供支持。

另请参阅有关lookbehind的重要说明

const s = "This is just\na simple sentence";
const regex = /(?<=This is)[^]*?(?=sentence)/;
const m = s.match(regex);

if (m) {
  console.log(m[0]);
}

In case of JavaScript you can use [^] to match any character including newlines.

Using the /s flag with a dot . to match any character also works, but is applied to the whole pattern and JavaScript does not support inline modifiers to turn on/off the flag.

To match as least as possible characters, you can make the quantifier non greedy by appending a question mark, and use a capture group to extract the part in between.

This is([^]*?)sentence

See a regex101 demo.

As a side note, to not match partial words you can use word boundaries like \bThis and sentence\b

const s = "This is just\na simple sentence";
const regex = /This is([^]*?)sentence/;
const m = s.match(regex);

if (m) {
  console.log(m[1]);
}


The lookaround variant in JavaScript is (?<=This is)[^]*?(?=sentence) and you could check Lookbehind in JS regular expressions for the support.

Also see Important Notes About Lookbehind.

const s = "This is just\na simple sentence";
const regex = /(?<=This is)[^]*?(?=sentence)/;
const m = s.match(regex);

if (m) {
  console.log(m[0]);
}

正则匹配两个字符串之间的所有字符

埖埖迣鎅 2025-02-12 14:51:29

您可以使用oracle regexp_like操作员。如果它在 listagg 列中存在,则查找匹配项(您的编号):

  • 由空间或open括号[(] [(
  • ]代码> [,)]
SELECT * 
FROM tab
WHERE REGEXP_LIKE(Listagg, '[ (]4[,)]')
  AND REGEXP_LIKE(Listagg, '[ (]9[,)]')

检查演示

You can use an easy pattern matching with Oracle REGEXP_LIKE operator. It looks for the match (your number) if it is present inside the Listagg column:

  • preceeded by either space or open parenthesis [ (]
  • followed by either comma or closed parenthesis [,)]
SELECT * 
FROM tab
WHERE REGEXP_LIKE(Listagg, '[ (]4[,)]')
  AND REGEXP_LIKE(Listagg, '[ (]9[,)]')

Check the demo here.

如何访问Oracle Listagg中的元素?

埖埖迣鎅 2025-02-11 12:11:08

不,没有打破,但是大多数小数部分必须近似

摘要

浮点算术算术算术确切的,不幸的是,它与我们通常的base-10数字表示不太匹配,因此,事实证明,我们经常给出它的输入,这些输入与我们所写的内容相比有些偏离。

即使是简单的数字,例如0.01、0.02、0.03、0.04 ... 0.24也不能像二进制分数一样表示。如果您计数0.01,.02,.03 ...,直到到达0.25之前,您将获得第一个分数,可以在base2 中表示。如果您尝试使用FP,则您的0.01将略有关闭,因此,将其中25个添加到精确的0.25的唯一方法是需要一系列涉及后卫碎片和圆形的因果关系。很难预测,所以我们举起双手说“ FP是不精确的”,,但这并不是真的。

我们不断地给出FP硬件在基本10中看起来很简单的东西,但是在基本2中重复分数。

这是如何发生的?

当我们以小数为单位编写时,每一个分数(具体来说,每个终止)十进制)是形式的合理数量

&nbsp;&nbsp;&nbsp; nbsp;&nbsp; nbsp;&nbsp;&nbsp;
a/(2 n x 5 m

在二进制中,我们只得到 2 n < /em>术语,也就是:

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a/2 n

因此,在十进制中,我们不能表示 1 / 3 。因为基本10包括2作为主要因素,所以我们可以写入二进制分数 的每个数字也可以写为基本10分数。但是,我们几乎没有写任何作为基础 10 的分数在二进制中表示。在0.01、0.02、0.03 ... 0.99的范围内,只能以我们的FP格式表示三个数字:0.25、0.50和0.75,因为它们是1/4、1/2,和3/4,仅使用2 n 术语的所有数字。

在基本10 中,我们不能表示 1 /3 。但是在二进制中,我们不能做 1 /10 1 / 3

因此,尽管每个二元分数都可以用小数为小数,但相反是不正确的。实际上,大多数小数分数在二进制中重复。

通常指示开发人员进行&lt; Epsilon 比较,更好的建议可能是圆形的积分值(在C库中:round()和roundf(),即以FP格式保持),然后进行比较。四舍五入到特定的小数分数长度可以解决大多数输出​​问题。

同样,关于实际数字迫切问题(FP是在早期,昂贵的计算机上发明的问题),宇宙的物理常数和所有其他测量值仅是相对较少的重要数字知道的,因此整个问题空间无论如何是“不精确的”。在这种应用中,FP“准确性”不是问题。

当人们试图将FP用于豆类计数时,整个问题确实会产生。它确实为此起作用,但是只有当您坚持积分价值时,哪种使用它的要点。 这就是为什么我们拥有所有那些小数分数软件库。

我喜欢 chris ,因为它描述了实际问题,而不仅仅是关于“不准确性”的通常手动挥舞。如果FP简单地“不准确”,那么我们可以修复,并且几十年前就可以做到这一点。我们没有的原因是因为FP格式紧凑且快速,这是处理大量数字的最佳方法。此外,这是空间年龄和军备竞赛的遗产,也是使用小型内存系统来解决非常缓慢的计算机来解决大问题的遗产。 (有时是1位存储的单个磁芯,但这是又故事。

结论,

如果您只是在银行计算豆子,那么首先使用小数字符串表示形式的软件解决方案非常有效。但是,您不能这样做量子染色体动力学或空气动力学。

No, not broken, but most decimal fractions must be approximated

Summary

Floating point arithmetic is exact, unfortunately, it doesn't match up well with our usual base-10 number representation, so it turns out we are often giving it input that is slightly off from what we wrote.

Even simple numbers like 0.01, 0.02, 0.03, 0.04 ... 0.24 are not representable exactly as binary fractions. If you count up 0.01, .02, .03 ..., not until you get to 0.25 will you get the first fraction representable in base2. If you tried that using FP, your 0.01 would have been slightly off, so the only way to add 25 of them up to a nice exact 0.25 would have required a long chain of causality involving guard bits and rounding. It's hard to predict so we throw up our hands and say "FP is inexact", but that's not really true.

We constantly give the FP hardware something that seems simple in base 10 but is a repeating fraction in base 2.

How did this happen?

When we write in decimal, every fraction (specifically, every terminating decimal) is a rational number of the form

a / (2n x 5m)

In binary, we only get the 2n term, that is:

           a / 2n

So in decimal, we can't represent 1/3. Because base 10 includes 2 as a prime factor, every number we can write as a binary fraction also can be written as a base 10 fraction. However, hardly anything we write as a base10 fraction is representable in binary. In the range from 0.01, 0.02, 0.03 ... 0.99, only three numbers can be represented in our FP format: 0.25, 0.50, and 0.75, because they are 1/4, 1/2, and 3/4, all numbers with a prime factor using only the 2n term.

In base10 we can't represent 1/3. But in binary, we can't do 1/10 or 1/3.

So while every binary fraction can be written in decimal, the reverse is not true. And in fact most decimal fractions repeat in binary.

Dealing with it

Developers are usually instructed to do < epsilon comparisons, better advice might be to round to integral values (in the C library: round() and roundf(), i.e., stay in the FP format) and then compare. Rounding to a specific decimal fraction length solves most problems with output.

Also, on real number-crunching problems (the problems that FP was invented for on early, frightfully expensive computers) the physical constants of the universe and all other measurements are only known to a relatively small number of significant figures, so the entire problem space was "inexact" anyway. FP "accuracy" isn't a problem in this kind of application.

The whole issue really arises when people try to use FP for bean counting. It does work for that, but only if you stick to integral values, which kind of defeats the point of using it. This is why we have all those decimal fraction software libraries.

I love the Pizza answer by Chris, because it describes the actual problem, not just the usual handwaving about "inaccuracy". If FP were simply "inaccurate", we could fix that and would have done it decades ago. The reason we haven't is because the FP format is compact and fast and it's the best way to crunch a lot of numbers. Also, it's a legacy from the space age and arms race and early attempts to solve big problems with very slow computers using small memory systems. (Sometimes, individual magnetic cores for 1-bit storage, but that's another story.)

Conclusion

If you are just counting beans at a bank, software solutions that use decimal string representations in the first place work perfectly well. But you can't do quantum chromodynamics or aerodynamics that way.

浮点数学破裂了吗?

埖埖迣鎅 2025-02-11 10:05:35

会话是一个单个连接,对应于MySQL Server中的一个线程,可以在show ProcessList中查看。

会话范围内有几件事:

  • 会话变量临时表
  • 事务临时表
  • 事务
  • 最后插入自动插入列生成的ID ID

时,该文档显示临时表仅适用于创建该端的客户端,这仅在相同的连接中含义。相同的MySQL用户可能还有其他连接,但是每个连接都是不同的会话。

A session is a single connection, corresponding to one thread in the MySQL Server, which can be viewed in SHOW PROCESSLIST.

There are several things that are scoped to the session:

  • Session variables
  • Temporary tables
  • Transactions
  • Last insert id generated for an auto-increment column

When the documentation says the temporary table is accessible only to the client that creates it, that means only in the same connection. There may be other connections for the same MySQL user, but each connection is a different session.

会话的客户是什么。在mysql中?

埖埖迣鎅 2025-02-11 05:11:20

如@Corralien所述,您最好对此进行矢量化。看到那个答案。但是要了解如何通过apply()函数来执行此操作:您可以:

def cpl_calc(x):
    if x['cost'] == 0:
        cpl = x['leads']
    else: 
        cpl = x['leads'] / x['cost']
     
    return cpl

data.apply(cpl_calc, axis=1)

0    0.066667
1    0.000000
2    0.100000

As @Corralien states, you are better off to vectorize this. See that answer. But to understand how to do this via an apply() function you could:

def cpl_calc(x):
    if x['cost'] == 0:
        cpl = x['leads']
    else: 
        cpl = x['leads'] / x['cost']
     
    return cpl

data.apply(cpl_calc, axis=1)

0    0.066667
1    0.000000
2    0.100000

具有两个值的lambda不起作用,错误:&lt; lambda&gt;()缺少1所需的位置参数:&#x27; y)

埖埖迣鎅 2025-02-09 14:08:13

如何设置初始窗口尺寸和中心(MAUI 7.0.59):

public partial class App : Application {

    public App() {
        InitializeComponent();
        MainPage = new AppShell();
    }

    protected override Window CreateWindow(IActivationState activationState) {
        var window = base.CreateWindow(activationState);
        window.Created += Window_Created;
        return window;
    }

    private async void Window_Created(object sender, EventArgs e) {
        const int defaultWidth = 1200;
        const int defaultHeight = 800;

        var window = (Window)sender;
        window.Width = defaultWidth;
        window.Height = defaultHeight;
        window.X = -defaultWidth;
        window.Y = -defaultHeight;

        await window.Dispatcher.DispatchAsync(() => {});

        var displayInfo = DeviceDisplay.Current.MainDisplayInfo;
        window.X = (displayInfo.Width / displayInfo.Density - window.Width) / 2;
        window.Y = (displayInfo.Height / displayInfo.Density - window.Height) / 2;
    }

}

How to set initial window size and center it (maui 7.0.59):

public partial class App : Application {

    public App() {
        InitializeComponent();
        MainPage = new AppShell();
    }

    protected override Window CreateWindow(IActivationState activationState) {
        var window = base.CreateWindow(activationState);
        window.Created += Window_Created;
        return window;
    }

    private async void Window_Created(object sender, EventArgs e) {
        const int defaultWidth = 1200;
        const int defaultHeight = 800;

        var window = (Window)sender;
        window.Width = defaultWidth;
        window.Height = defaultHeight;
        window.X = -defaultWidth;
        window.Y = -defaultHeight;

        await window.Dispatcher.DispatchAsync(() => {});

        var displayInfo = DeviceDisplay.Current.MainDisplayInfo;
        window.X = (displayInfo.Width / displayInfo.Density - window.Width) / 2;
        window.Y = (displayInfo.Height / displayInfo.Density - window.Height) / 2;
    }

}

MAUI .NET设置窗口大小

埖埖迣鎅 2025-02-09 13:00:26

您可以将调用删除str(),然后通过使用'_'' * len(word)生成与原始字符串相同的下划线的字符串。

import random

list_of_words = ["Hello"]
word = random.choice(list_of_words)
print('_' * len(word))

这输出:

_____

You can remove the call to str() and then generate a string of underscores that has the same length as the original string by using '_' * len(word).

import random

list_of_words = ["Hello"]
word = random.choice(list_of_words)
print('_' * len(word))

This outputs:

_____

对于x in'hello hello quot;打印

埖埖迣鎅 2025-02-08 18:32:42

这似乎是一个临时问题。 <

This seems to be a temporary issue. See here.

Chrome error_timed_out中的最新版本

埖埖迣鎅 2025-02-08 14:03:17

问题在于,在tf.gradienttape的上下文中,您对层的权重进行的更改没有直接连接到模型的输出。您可以使用一个简单的自定义层解决此问题:

import tensorflow as tf

class DenseLayer(tf.keras.layers.Layer):
    def __init__(self, units=1):
        super(DenseLayer, self).__init__()
        self.units = units
    def build(self, input_shape):
        self.w = self.add_weight("kernel",
                              shape=[int(input_shape[-1]),
                                      self.units], trainable=True)
        self.b = self.add_weight(shape=(self.units,), initializer="zeros", trainable=True)
        self.bits = self.add_weight(name="x1", shape=[int(input_shape[-1]),
                                      self.units], initializer=tf.keras.initializers.ones(), trainable=True)

    def call(self, inputs):
        return tf.nn.relu(tf.matmul(inputs, (self.w + self.bits + 1.0)) + self.b)

dense_layer = DenseLayer(1)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(1,1)))
model.add(dense_layer)
model.add(tf.keras.layers.Dense(2, activation='softmax'))
print(model.summary())
dataset = tf.data.Dataset.from_tensor_slices((tf.random.normal((50, 1, 1)), tf.random.uniform((50, ), maxval=2, dtype=tf.int32))).batch(2)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)
for i, (x_batch_train, y_batch_train) in enumerate(dataset):
    with tf.GradientTape() as tape:
        y = model(x_batch_train, training = True)
        loss = loss_fn(y_batch_train, y)
        val = tape.gradient(loss, model.trainable_weights)
        for v in val:
            print(v)
    optimizer.apply_gradients(zip(val, model.trainable_variables))

The problem is that the changes you are making to the layer's weights have no direct connection to the output of the model in the context of tf.GradientTape and are therefore not tracked. You could solve this with a simple custom layer:

import tensorflow as tf

class DenseLayer(tf.keras.layers.Layer):
    def __init__(self, units=1):
        super(DenseLayer, self).__init__()
        self.units = units
    def build(self, input_shape):
        self.w = self.add_weight("kernel",
                              shape=[int(input_shape[-1]),
                                      self.units], trainable=True)
        self.b = self.add_weight(shape=(self.units,), initializer="zeros", trainable=True)
        self.bits = self.add_weight(name="x1", shape=[int(input_shape[-1]),
                                      self.units], initializer=tf.keras.initializers.ones(), trainable=True)

    def call(self, inputs):
        return tf.nn.relu(tf.matmul(inputs, (self.w + self.bits + 1.0)) + self.b)

dense_layer = DenseLayer(1)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(1,1)))
model.add(dense_layer)
model.add(tf.keras.layers.Dense(2, activation='softmax'))
print(model.summary())
dataset = tf.data.Dataset.from_tensor_slices((tf.random.normal((50, 1, 1)), tf.random.uniform((50, ), maxval=2, dtype=tf.int32))).batch(2)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)
for i, (x_batch_train, y_batch_train) in enumerate(dataset):
    with tf.GradientTape() as tape:
        y = model(x_batch_train, training = True)
        loss = loss_fn(y_batch_train, y)
        val = tape.gradient(loss, model.trainable_weights)
        for v in val:
            print(v)
    optimizer.apply_gradients(zip(val, model.trainable_variables))

TF.Gradienttape无梯度

埖埖迣鎅 2025-02-08 12:27:44

您可以创建一个最简单的项目,并在数据库中手动存储一些数据。

模型:

public class Member
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

控制器:

public async Task<IActionResult> Test()
{
     var mumber = await _context.Member.ToListAsync();
     return View(await _context.Member.ToListAsync());
}

查看:

@model List<Member>
<style>
    .card:hover {
        box-shadow: -1px 9px 40px -12px #808080;
    }
</style>
@foreach (var Member in Model)
{
    <div class="row">
        <div class="card" style=" width:20em;margin:10px;">
           
            <div class="card-body">
                <div class="card-title">
                    <h2>@Member.Name</h2>
                </div>
                <div class="card-text">
                    <p>@Member.Address</p>
                </div>
                <a href="#" class="btn btn-primary">Read More</a>
            </div>
        </div>
    </div>

}

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$('.card').hover(
    function() {
        $(this).animate({
            marginTop: "-=1%",
            marginBottom: "+=1%"
        }, 200)
    },
    function() {
        $(this).animate({
            marginTop: "-=1%",
            marginBottom: "+=1%"
        })
    }
)
</script>

成员表:

”“在此处输入图像说明”

确认其正常加载并查看问题是否仍然发生。如果它可以正常运行,则可以继续并添加所需的其他逻辑。

You can create a simplest project and manually store some data in the database like this.

Model:

public class Member
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

Controller:

public async Task<IActionResult> Test()
{
     var mumber = await _context.Member.ToListAsync();
     return View(await _context.Member.ToListAsync());
}

View:

@model List<Member>
<style>
    .card:hover {
        box-shadow: -1px 9px 40px -12px #808080;
    }
</style>
@foreach (var Member in Model)
{
    <div class="row">
        <div class="card" style=" width:20em;margin:10px;">
           
            <div class="card-body">
                <div class="card-title">
                    <h2>@Member.Name</h2>
                </div>
                <div class="card-text">
                    <p>@Member.Address</p>
                </div>
                <a href="#" class="btn btn-primary">Read More</a>
            </div>
        </div>
    </div>

}

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$('.card').hover(
    function() {
        $(this).animate({
            marginTop: "-=1%",
            marginBottom: "+=1%"
        }, 200)
    },
    function() {
        $(this).animate({
            marginTop: "-=1%",
            marginBottom: "+=1%"
        })
    }
)
</script>

Member Table:

enter image description here

Verify that it loads normally and see if the problem still occurs.If it works fine, you can go ahead and add other logic you want.

Bootstrap卡ahown ahown错误nullReferenceException:对象引用未设置为对象的实例

埖埖迣鎅 2025-02-08 09:02:53

我会这样做:

ALTER TABLE erp.tb_customer 
ADD COLUMN password_cryp char(100);

--CREATE EXTENSION pgcrypto;

CREATE OR REPLACE PROCEDURE erp.col_cryp() AS $
DECLARE
  _row record;
BEGIN
    FOR _row IN (
        SELECT cust_cif FROM erp.tb_customer
        )
    LOOP
        UPDATE erp.tb_customer
        SET password_cryp = crypt('cust_cif', gen_salt('md5'));
    END LOOP;
END;
$LANGUAGE plpgsql;

CALL erp.col_cryp();

要测试它,您可以尝试:

SELECT ("password_cryp " = 'copy here the generated code on the table') AS IsMatch FROM erp.tb_customer;

希望它有效!

I would do it this way:

ALTER TABLE erp.tb_customer 
ADD COLUMN password_cryp char(100);

--CREATE EXTENSION pgcrypto;

CREATE OR REPLACE PROCEDURE erp.col_cryp() AS $
DECLARE
  _row record;
BEGIN
    FOR _row IN (
        SELECT cust_cif FROM erp.tb_customer
        )
    LOOP
        UPDATE erp.tb_customer
        SET password_cryp = crypt('cust_cif', gen_salt('md5'));
    END LOOP;
END;
$LANGUAGE plpgsql;

CALL erp.col_cryp();

To test it you can try:

SELECT ("password_cryp " = 'copy here the generated code on the table') AS IsMatch FROM erp.tb_customer;

Hope it works!

使用crypt创建一个带有密码的新列

埖埖迣鎅 2025-02-08 04:54:47

删除之间的空格> 添加边距 - 左:自动到相​​关图标。

.icon_item {
    display: flex;
  
}

.icon_item:after {
  font-family: fontAwesome;
  content: '\f107';
  margin-left:auto;
}

.icon_item.visible:after {
  font-family: fontAwesome;
  content: '\f068';
}

.icon_item:before {
 font-family: fontAwesome;
 content: '\f1ec';
 margin-right: 10px;
 width: 22px;
 height: 22px;
 display: flex;
 align-items: center;
 justify-content: center;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

<div class="btnDrop">
 <span class="icon_item">Calculator</span>
</div>

Remove space-between and add margin-left:auto to the relevant icon.

.icon_item {
    display: flex;
  
}

.icon_item:after {
  font-family: fontAwesome;
  content: '\f107';
  margin-left:auto;
}

.icon_item.visible:after {
  font-family: fontAwesome;
  content: '\f068';
}

.icon_item:before {
 font-family: fontAwesome;
 content: '\f1ec';
 margin-right: 10px;
 width: 22px;
 height: 22px;
 display: flex;
 align-items: center;
 justify-content: center;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

<div class="btnDrop">
 <span class="icon_item">Calculator</span>
</div>

如何将左侧的前两个元素与右侧的最后两个元素对齐

埖埖迣鎅 2025-02-08 01:51:17

您的示例数据

library(raster)
r <- raster(xmn=0,xmx=5,ymn=0,ymx=5,res=1)
set.seed(123)
list_abcd <- replicate(4, setValues(r, sample(1:5,25,replace=T)))
list_efgh <- replicate(4, setValues(r, sample(1:5,25,replace=T)))
list_ijkl <- replicate(4, setValues(r, sample(1:5,25,replace=T)))   
list_all <- list(list_abcd,list_efgh,list_ijkl)
names(list_all) <- c("abcd", "efgh", "ijkl")

解决方案,创建一个rasterstack并使用stackapply

x <- stack(unlist(list_all))
i <- rep(1:4, 3)
s <- stackApply(x, i, mean)
s
#class      : RasterBrick 
#dimensions : 5, 5, 25, 4  (nrow, ncol, ncell, nlayers)
#resolution : 1, 1  (x, y)
#extent     : 0, 5, 0, 5  (xmin, xmax, ymin, ymax)
#crs        : +proj=longlat +datum=WGS84 +no_defs 
#source     : memory
#names      :  index_1,  index_2,  index_3,  index_4 
#min values : 1.333333, 2.000000, 1.000000, 1.666667 
#max values : 4.666667, 5.000000, 4.666667, 4.333333 

现在让我们使用terra (更换raster)。我们从三个spatraster s(类似于栅格挡板)

library(terra)
rr <- rast(xmin=0,xmax=5,ymin=0,ymax=5,res=1)
set.seed(123)
abcd <- replicate(4, setValues(rr, sample(1:5,25,replace=T))) |> rast()
efgh <- replicate(4, setValues(rr, sample(1:5,25,replace=T))) |> rast()
ijkl <- replicate(4, setValues(rr, sample(1:5,25,replace=T))) |> rast()
# the above is equivalent to: abcd <- c(a,b,c,d)

1:组合到单个spatraster 中,然后使用tapp

rall <- c(abcd, efgh, ijkl) 
z1 <- tapp(rall, rep(1:4, 3), "mean")

解决方案2:集合到一个spatrasterdataset并使用app

rsd <- sds(abcd, efgh, ijkl) 
z2 <- app(rsd, "mean")

解决方案3:使用平均直接

z3 <- mean(abcd, efgh, ijkl) 

后来:从您的评论中,我收集您的错误确实在创建这些列表中。如果我很好地了解您,则有代表模型的 n 文件,每个文件都有2*100层;您想平均在模型中平均每一层(年级水状态)的值;因此,您最终获得了200层的单个栅格数据集(或2个带有100层的数据集)。您可以通过这样的事情来实现这一目标:

 library(terra)
 ff <- list.files(pattern="nc$")  
 sd <- sds(ff)
 x <- app(sd, mean)

或者,如果灌溉/雨水是单独的子数据集,则类似于

 library(terra)
 ff <- list.files(pattern="nc$")  
 sd <- lapply(ff, \(i) rast(i, "irrigated")) |> sds()
 # or sd <- lapply(ff, \(i) rast(i, 1)) |> sds()
 x <- app(sd, mean)

一些示例数据

f <- system.file("ex/logo.tif", package="terra")
sd <- sds(c(f,f,f))
x <- app(sd, mean)

Your example data

library(raster)
r <- raster(xmn=0,xmx=5,ymn=0,ymx=5,res=1)
set.seed(123)
list_abcd <- replicate(4, setValues(r, sample(1:5,25,replace=T)))
list_efgh <- replicate(4, setValues(r, sample(1:5,25,replace=T)))
list_ijkl <- replicate(4, setValues(r, sample(1:5,25,replace=T)))   
list_all <- list(list_abcd,list_efgh,list_ijkl)
names(list_all) <- c("abcd", "efgh", "ijkl")

Solution, create a single RasterStack and use stackApply

x <- stack(unlist(list_all))
i <- rep(1:4, 3)
s <- stackApply(x, i, mean)
s
#class      : RasterBrick 
#dimensions : 5, 5, 25, 4  (nrow, ncol, ncell, nlayers)
#resolution : 1, 1  (x, y)
#extent     : 0, 5, 0, 5  (xmin, xmax, ymin, ymax)
#crs        : +proj=longlat +datum=WGS84 +no_defs 
#source     : memory
#names      :  index_1,  index_2,  index_3,  index_4 
#min values : 1.333333, 2.000000, 1.000000, 1.666667 
#max values : 4.666667, 5.000000, 4.666667, 4.333333 

Now let's do this with terra (the replacement of raster). We start with three SpatRasters (similar to a RasterStack)

library(terra)
rr <- rast(xmin=0,xmax=5,ymin=0,ymax=5,res=1)
set.seed(123)
abcd <- replicate(4, setValues(rr, sample(1:5,25,replace=T))) |> rast()
efgh <- replicate(4, setValues(rr, sample(1:5,25,replace=T))) |> rast()
ijkl <- replicate(4, setValues(rr, sample(1:5,25,replace=T))) |> rast()
# the above is equivalent to: abcd <- c(a,b,c,d)

Solution 1: Combine into a single SpatRaster and use tapp

rall <- c(abcd, efgh, ijkl) 
z1 <- tapp(rall, rep(1:4, 3), "mean")

Solution 2: Combine into a SpatRasterDataset and use app

rsd <- sds(abcd, efgh, ijkl) 
z2 <- app(rsd, "mean")

Solution 3: Use mean directly

z3 <- mean(abcd, efgh, ijkl) 

Later: from your comment I gather the mistake you make is indeed in creating these lists. If I understand you well you have n files representing models, each with 2*100 layers; and you want to average the values of each layer (year & water status) across models; so that you end up with a single raster dataset of 200 layers (or 2 datasets with 100 layers). You can achieve that with something like this:

 library(terra)
 ff <- list.files(pattern="nc
quot;)  
 sd <- sds(ff)
 x <- app(sd, mean)

Or, if irrigated/rainfed are separate sub-datasets, something like

 library(terra)
 ff <- list.files(pattern="nc
quot;)  
 sd <- lapply(ff, \(i) rast(i, "irrigated")) |> sds()
 # or sd <- lapply(ff, \(i) rast(i, 1)) |> sds()
 x <- app(sd, mean)

With some example data

f <- system.file("ex/logo.tif", package="terra")
sd <- sds(c(f,f,f))
x <- app(sd, mean)

多层射手列表 - 在R中执行代数

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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