默认情况下,JSON数据源可以使用默认 InferSchema
选项从输入文件中推断架构。因此,如果将JSON存储在文件中,则无需自己定义它:
val df = spark.read.json("<PATH_to_JSON_File>", multiLine = "true")
仅当您的JSON记录跨越多行时,才需要使用 Multiline =“ True”
。
示例:
//read json file into dataframe
val df = spark.read.json("src/main/resources/myJsonFile.json")
df.printSchema()
df.show(false)
您仍然可以自己定义模式,但请注意,您的数组不一致。内部的键具有不同的名称,但它们也是不同的元素。您无法在JSON中的封闭数组中使用不同的键定义2个元素。这就像定义不同类型的2个要素。
因此,我认为您的JSON应该看起来像这样:“:[{“ A”:“ 6”,“ B”:7}]”
在这种情况下,您的模式应为:
val schema = ArrayType(StructType(Array(
(StructField("a", StringType, true),
(StructField("b", StringType, true)
)), false)
false
字段表示您的数组不能接受 null
元素,但仍然可以将 null
放入列中。
错误检查失败:您正在提供一个预期整数的字符串。除非您为 device.create()
提供接口,否则它是不确定的。检查文档并确保您的输入数据具有正确的类型。
编辑:以下想法是伪造的 也可能会与您的输入混合:在像您一样使用速记对象表示法时,请确保您的参数具有正确的顺序。根据框架,您的输入可能只是错误的语法,因为您本质上是在没有键的情况下初始化对象,但是, img
。如果您的框架无法纠正这一点,这也可能是错误源。
但同样,如果没有更多有关该功能呼叫期望的信息以及您的参数类型的信息,请调试是算命的。
也可以使用async_playwright尝试相同的方法:
import asyncio
from playwright.async_api import async_playwright
import time
# async def handle_dialog(dialog):
# if dialog.message == 'You will be redirected to employer Login Portal.':
# await dialog.dismiss()
async def main():
# Create a browser instance.
async with async_playwright() as playwright:
browser = await playwright.firefox.launch(headless=False)
#https://playwright.dev/docs/downloads
context = await browser.new_context()
# chromium_context = playwright.chromium.cast(context)
# await chromium_context.set_browser_context_option("downloads", False)
# Create a new page.
page = await context.new_page()
# Navigate to the specified URL.
await page.goto('https://www.google.com/')
#https://stackoverflow.com/questions/72493916/closing-a-confirm-popup-with-
playwright-in-python/72513920#72513920
page.on("dialog", lambda dialog: dialog.dismiss())
# Wait for the page to load.
await page.wait_for_load_state('networkidle', timeout=10000) # 10 secs
# Click on the "Sign In" button.
await page.wait_for_selector('css=#modal-content > span')
mod = page.locator('css=#modal-content > span')
await mod.click()
await page.wait_for_selector('css=body > div._bodyMID.pdGridM > div >
div.col-md-9.col-sm-8._action4Mob.homesearch > div.service-listnew > ul >
li.service1.single-ser > a')
employerlogin = page.locator('css=body > div._bodyMID.pdGridM > div >
div.col-md-9.col-sm-8._action4Mob.homesearch > div.service-listnew > ul >
li.service1.single-ser > a')
await employerlogin.click()
time.sleep(30)
#await page.close()
# close the context
#await context.close()
# Close the browser.
#await browser.close()
asyncio.run(main()) # one time callable
0。在转换后保存整数类型,
如Alex Riley的答案所示, pd.to_numeric(...,errors ='coerce')
将整数转换为浮点。
要保留整数,您必须使用可无效的整数dtype,例如'int64'
。一个选项是呼叫 .convert_dtypes()
如Alex Riley的答案中。或者只使用 .astype('int64')
。
自PANDAS 2.0以来的另一个选项是传递 dtype_backend
参数,该参数允许您在一个函数调用中转换DTYPE。
df = pd.DataFrame({'A': ['#DIV/0!', 3, 5]})
df['A'] = pd.to_numeric(df['A'], errors='coerce').convert_dtypes()
df['A'] = pd.to_numeric(df['A'], errors='coerce').astype('Int64')
df['A'] = pd.to_numeric(df['A'], errors='coerce', dtype_backend='numpy_nullable')
以上所有这些都会进行以下转换:
的字符串表示,则将长浮子的字符串表示为数字值
1。如果列包含需要用精确评估的真正长浮子 ( float 将在15位数字和
pd.to_numeric
更加不精确之后将它们围住,然后使用 DECIMAL
从内置的 DECIMAL
库中使用。列的dtype将为对象
,但 DECIMAL.DECIMAL
支持所有算术操作,因此您仍然可以执行诸如算术和比较操作员等矢量化操作。
from decimal import Decimal
df = pd.DataFrame({'long_float': ["0.1234567890123456789", "0.123456789012345678", "0.1234567890123456781"]})
df['w_float'] = df['long_float'].astype(float) # imprecise
df['w_Decimal'] = df['long_float'].map(Decimal) # precise
在上面的示例中, float
将所有这些转换为相同的数字,而 DECIMAL
保持差异:
df['w_Decimal'] == Decimal(df.loc[1, 'long_float']) # False, True, False
df['w_float'] == float(df.loc[1, 'long_float']) # True, True, True
将长整数的字符串表示为整数
2。默认情况下 , astype(int)转换为
int32
,如果一个数字特别长(例如电话号码),则无法使用( OverFloperRor
);尝试'int64'
(甚至 float
):
df['long_num'] = df['long_num'].astype('int64')
在旁注,如果您获得 setterwithCopyWarning
,请打开折线,然后打开复印件。模式(请参阅此答案以获取更多信息),然后再做任何事情。例如,如果您将 col1
和 col2
转换为float dtype,则执行:
pd.set_option('mode.copy_on_write', True)
df[['col1', 'col2']] = df[['col1', 'col2']].astype(float)
# or use assign to overwrite the old columns and make a new copy
df = df.assign(**df[['col1', 'col2']].astype(float))
3。将整数转换为timeDERTA
,也可以将长字符串/整数date -dateTime或TimeDETTA,in在哪种情况下,请使用 to_datetime
或 to_timedelta
转换为dateTime/timeDELTA dtype:
df = pd.DataFrame({'long_int': ['1018880886000000000', '1590305014000000000', '1101470895000000000', '1586646272000000000', '1460958607000000000']})
df['datetime'] = pd.to_datetime(df['long_int'].astype('int64'))
# or
df['datetime'] = pd.to_datetime(df['long_int'].astype(float))
df['timedelta'] = pd.to_timedelta(df['long_int'].astype('int64'))
4。将TIMSEDELTA转换为数字
,以执行反向操作(Convert dateTime/timeDelta到数字),将其视为'int64'
。如果您要建立一个以某种方式将时间(或DateTime)作为数字值包含的机器学习模型,这可能很有用。只要确保原始数据是字符串,则必须将它们转换为timedelta或dateTime,然后再转换为数字。
df = pd.DataFrame({'Time diff': ['2 days 4:00:00', '3 days', '4 days', '5 days', '6 days']})
df['Time diff in nanoseconds'] = pd.to_timedelta(df['Time diff']).view('int64')
df['Time diff in seconds'] = pd.to_timedelta(df['Time diff']).view('int64') // 10**9
df['Time diff in hours'] = pd.to_timedelta(df['Time diff']).view('int64') // (3600*10**9)
5。将日期时间转换为日期时间的数字
,DateTime的数字视图是DateTime和Unix Epoch(1970-01-01)之间的时间差。
df = pd.DataFrame({'Date': ['2002-04-15', '2020-05-24', '2004-11-26', '2020-04-11', '2016-04-18']})
df['Time_since_unix_epoch'] = pd.to_datetime(df['Date'], format='%Y-%m-%d').view('int64')
6。 astype
比 to_numeric
更快
df = pd.DataFrame(np.random.default_rng().choice(1000, size=(10000, 50)).astype(str))
df = pd.concat([df, pd.DataFrame(np.random.rand(10000, 50).astype(str), columns=range(50, 100))], axis=1)
%timeit df.astype(dict.fromkeys(df.columns[:50], int) | dict.fromkeys(df.columns[50:], float))
# 488 ms ± 28 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit df.apply(pd.to_numeric)
# 686 ms ± 45.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
尝试将其
...
late Future<ImageProvider> imageProviderFuture;
@override
void initState() {
imageProviderFuture = Buttons.getGroupchatImage(widget.groupchat.Id, context),
super.initState();
}
...
//in your build
// future call imageProviderFuture
FutureBuilder<ImageProvider>(
future: imageProviderFuture,
)
应用于其余的地方。
ps请参阅此 link
看起来您只需要一个简单的案例表达式,
select Article, [Desc.],
case when UM = 'PC' then Value end ValuePC,
case when UM = 'CT' then Value end ValueCT
from t;
考虑一个极为基本的示例:
irb(main):003:0> a = [1, 2, 3]
=> [1, 2, 3]
irb(main):004:0> a.each { |x| p x }
1
2
3
=> [1, 2, 3]
irb(main):005:0>
#each
方法
正在返回枚举
对象。
如果我将其包裹在方法中,则该方法将返回最后一个表达式,该表达式评估 enumerable
对象 a
。
irb(main):006:0> def foo(a)
irb(main):007:1> a.each { |x| puts x }
irb(main):008:1> end
=> :foo
irb(main):009:0> foo([1, 2, 3])
1
2
3
=> [1, 2, 3]
irb(main):010:0>
您可以尝试制作在启动时运行的批处理脚本。此批处理脚本将 cd
到包含要运行的Python文件的目录,并最终通过执行 python main.py
来运行Python文件。
据我了解,您的问题是如何实现文本框颜色使用 systemcolors.control
的默认值的视觉状态。 /code>状态和不同的自定义颜色时。
我知道的最简单方法是处理 readonlychanged
textbox
控件的事件。例如:
public Form1()
{
InitializeComponent();
textBox2.ReadOnlyChanged += (sender, e) =>
{
textBox2.BackColor = textBox2.ReadOnly ? SystemColors.Control : Color.Blue;
};
}
并在设置自定义背景颜色时首先检查状态:
private void button3_Click(object sender, EventArgs e)
{
textBox2.BackColor = textBox2.ReadOnly ? SystemColors.Control : Color.Blue;
}
如评论中提到的那样,简单,快速和肮脏的解决方案是
std::sort(first,last, [](const auto& a,const auto& b) {
return titleSort(&a,&b) < 0;
});
因为 std :: sort
的比较器应返回 true
时 a&lt; b
和 false
否则。当 a&lt; b
然后 titlesort
返回 -1
和 0
或或 1
否则。因此,您要映射 1
为 true
和 0
和 1
to false
,和&lt; 0
这样做。
您还需要考虑 std :: sort
的比较器必须符合指定要求比较。典型的比较可以做到这一点,但是当它们不使用 std :: sort
的情况下,不确定。我没有发现 QSort
的类似要求。
您必须添加内容类型
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer "+token);
.... your code
var body="{\"storage_id\":\"bl_1\",\"product_id\":\"67564668\",\"variant_id\":1055421650,\"name\":\"42\",\"quantity\":5,\"price_brutto\":599.99,\"ean\":29193201490}";
request.AddParameter("application/json",body,ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var json=response.Content;
我认为我们也可以这样做
[ r for r in [x] if 1 < x < 5 ]
我是Mark Rotteveel的#6建议的粉丝(在上面的评论中):
- 下载时使用临时名称,
- 在下载完成后重命名。
看起来像:
- FTP下载线程写入所有文件,上面有一些添加的扩展名 - 也许
.pending
- 但无论您想要什么名称。 - 下载文件时 - 说
some.pdf
- &nbsp; ftp下载线程将文件写入some.pdf.pend.pending
- 当FTP下载线程完成文件时,最后一步是文件重命名操作 - 这是确保仅准备处理“完成”文件的机制。因此,它将文件下载到
some.pdf.perding
,然后将其重命名为some.pdf
。 - 读者线程查找文件,忽略了任何匹配的
*。待处理
我使用此方法构建了系统,它们效果很好。相比之下,我还与更复杂的系统合作,这些系统试图跨线程协调,并且这些系统通常无法正常工作。
随着时间的流逝,任何软件系统都会有错误。 Edsger Dijkstra很好地抓住了这一点:
“如果调试是删除软件错误的过程,则编程必须是将其放入的过程。”
但是,很难理解程序正确性现在 - &nbsp;当该程序仍处于设计阶段时,
而且尚未建立 - &nbsp;当生产中损坏的情况时,要理解正确性(由于错误)时,将是更难的。
也就是说,当事情被打破并且您在时间的压力下找到根本原因(并修复它!),即使我们中最好的人都会处于不利地位
具有复杂的(与简单)系统。
使用临时名称的方法很容易理解,这应该最大程度地减少代码复杂性,从而使其更容易实现。
反过来,维护和错误修复也应该更容易。
保持简单 - 让文件系统为您提供帮助。
您可以喜欢:
<script th:inline="javascript">
$('#' + [[${answerList.answer_id}]] + 'answer_id').text();
</script>
我们可以使用块(arr,size)
arr.length
小于或等于size
,则不再有块。 的Singleton块[arr]
否则(归纳)arr.length
大于size> size
,至少有一个块。将一个块从阵列的左侧切下来,并将其预先放置为递归子问题的结果。可视化评估 -
We can write
chunk(arr, size)
using inductive reasoning -arr.length
is less than or equal tosize
, there are no more chunks to make. Return the singleton chunk of[ arr ]
arr.length
is greater thansize
, there is at least one chunk to make. Slice one chunk off the left of the array and prepend it to the result of the recursive sub-problem.Visualize the evaluation -
如何将和数组分为n数组JavaScript