我的原始数据以表格格式显示.它包含来自不同变量的观察.每次观察时都有变量名,时间戳和当时的值.
变量[string],Time [datetime],Value [float]
数据作为Parquet存储在HDFS中并加载到Spark Dataframe(df)中.从该数据帧.
现在我想为每个变量计算默认统计数据,如均值,标准差等.之后,一旦检索到Mean,我想过滤/计算那些紧邻Mean的变量值.
因此,我需要先得到每个变量的均值.这就是我使用GroupBy获取每个变量(不是整个数据集)的统计信息的原因.
df_stats = df.groupBy(df.Variable).agg( \
count(df.Variable).alias("count"), \
mean(df.Value).alias("mean"), \
stddev(df.Value).alias("std_deviation"))
Run Code Online (Sandbox Code Playgroud)
通过每个变量的均值,我可以过滤那些围绕均值的特定变量的值(只是计数).因此,我需要该变量的所有观察值(值).这些值位于原始数据帧df中,而不是聚合/分组数据帧df_stats中.
最后,我想要一个像聚合/分组df_stats这样的数据帧,并使用新列"count_around_mean".
我在考虑使用df_stats.map(...)或df_stats.join(df,df.Variable).但我被困在红色箭头上:(
问题:你怎么会意识到这一点?
临时解决方案:同时我正在使用基于您的想法的解决方案.但是stddev范围2和3的范围函数不起作用.它总是产生一个
AttributeError表示NullType没有_jvm
from pyspark.sql.window import Window
from pyspark.sql.functions import *
from pyspark.sql.types import *
w1 = Window().partitionBy("Variable")
w2 = Window.partitionBy("Variable").orderBy("Time")
def stddev_pop_w(col, w):
#Built-in stddev doesn't support windowing
return sqrt(avg(col * col).over(w) - pow(avg(col).over(w), 2))
def isInRange(value, mean, stddev, radius):
try:
if (abs(value - mean) < radius * stddev): …Run Code Online (Sandbox Code Playgroud) 我试图在代码中创建一个 ImageView,设置图像资源,然后将 ImageView 作为子视图添加到我的主视图中。我发现的所有示例都使用了布局。但在我的视图的构造函数中,我不知道如何做到这一点。
以下是代码片段:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CanvasView(this));
}
}
Run Code Online (Sandbox Code Playgroud)
风景:
public class CanvasView extends SurfaceView implements SurfaceHolder.Callback {
public CanvasView(Context context) {
super(context);
SurfaceHolder sh = getHolder();
sh.addCallback(this);
ImageView iv = new ImageView(context);
iv.setImageResource(R.drawable.wand);
// how to add iv to myself?
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用与我的Android应用程序相关的Google App Engine端点.在我的一个端点中,我有一个方法,它采用Base64编码的图像,然后存储在Blobstore中.检索图像是通过Google ImageService的服务URL完成的.
所以,我有两个问题.首先,我不推荐使用我正在使用的Blobstore File API.其次,调用非常慢,因为服务器在存储blob时同步工作,稍后在serve-url和blob-key上工作.
所以我的问题是,如何更改代码以使用Google(servlets)提出的Blobstore,但在Android代码中继续使用我非常好的Endpoint.有没有办法在不使用HttpRequest类的情况下继续使用该方法?
简而言之:
这是我的代码.
从Android客户端发送到Google应用引擎的实体.
@Entity
public class Image {
@Id
private int id = -1;
private byte[] data;
private String mimeType;
private int width;
private int height;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String …Run Code Online (Sandbox Code Playgroud) java google-app-engine android blobstore google-cloud-endpoints
想象一个大型数据集(> 40GB镶木地板文件),其中包含数千个变量的值观察值(三元组(变量,时间戳,值)).
现在想一下您只对500个变量的子集感兴趣的查询.并且您想要检索特定时间点(观察窗口或时间范围)的变量的观察值(值 - >时间序列).这样有一个开始和结束时间.
如果没有分布式计算(Spark),您可以像这样编写代码:
for var_ in variables_of_interest:
for incident in incidents:
var_df = df_all.filter(
(df.Variable == var_)
& (df.Time > incident.startTime)
& (df.Time < incident.endTime))
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何使用Spark/PySpark做到这一点?我在考虑:
预期产量应为:
incident1 --> dataframe 1
incident2 --> dataframe 2
...
Run Code Online (Sandbox Code Playgroud)
其中数据帧1包含所有变量及其在事件1和数据帧2的时间范围内的观测值,这些值在事件2的时间范围内.
我希望你有这个主意.
UPDATE
我尝试编写基于思路#1的解决方案和来自zero323给出的答案的代码.工作很顺利,但我想知道如何在最后一步中将其汇总/分组到事件中?我尝试为每个事件添加一个序号,但后来我在最后一步中遇到了错误.如果您可以查看和/或完成代码,那将会很酷.因此我上传了示例数据和脚本.环境是Spark 1.4(PySpark):
这篇文章建立在这篇文章的基础上。
我得到了一个 Pandas 数据框,其中包含城市的地理坐标(大地坐标)作为经度和纬度。
import pandas as pd
df = pd.DataFrame([{'city':"Berlin", 'lat':52.5243700, 'lng':13.4105300},
{'city':"Potsdam", 'lat':52.3988600, 'lng':13.0656600},
{'city':"Hamburg", 'lat':53.5753200, 'lng':10.0153400}]);
Run Code Online (Sandbox Code Playgroud)
对于每个城市,我都试图找到最近的另外两个城市。因此我尝试了 scipy.spatial.KDTree。为此,我必须将大地坐标转换为 3D 笛卡尔坐标(ECEF = 以地球为中心、以地球固定):
from math import *
def to_Cartesian(lat, lng):
R = 6367 # radius of the Earth in kilometers
x = R * cos(lat) * cos(lng)
y = R * cos(lat) * sin(lng)
z = R * sin(lat)
return x, y, z
df['x'], df['y'], df['z'] = zip(*map(to_Cartesian, df['lat'], df['lng']))
df
Run Code Online (Sandbox Code Playgroud)
这给我这个:
这样我就可以创建 KDTree:
coordinates = …Run Code Online (Sandbox Code Playgroud) 我在两个 XY 点(p1 和 p2)和该线外的第三个 XY 点(p3)之间有一条线/向量。根据这篇文章,我知道如何获得该点到线的距离。但我实际上要寻找的是该线上的一个点 (p4),它与第三个点 (p3) 的距离 (d) 最小。我找到了这篇文章,但我觉得这不是正确的解决方案。也许 Numpy 或 Python 中包含了一些东西?
根据@allo,我尝试了以下操作。您可以将我的代码下载为Python 文件或Jupyter Notebook(都是 Python3)。
points = [[1, 1], [3, 1], [2.5, 2], [2.5, 1]]
import matplotlib.pyplot as plt
%matplotlib inline
fig, ax = plt.subplots()
fig.set_size_inches(6,6)
x, y = zip(*points[:2])
l1, = ax.plot(x,y, color='blue')
scatter1 = ax.scatter(x=x,y=y, color='blue', marker='x', s=80, alpha=1.0)
x, y = zip(*points[2:])
l2, = ax.plot(x,y, color='red')
scatter2 = ax.scatter(x=x,y=y, color='red', marker='x', s=80, alpha=1.0)
p1 …Run Code Online (Sandbox Code Playgroud) 我有一个包含多个列的 DataFrame,其中一个是 datetime 类型。有时,此列通过df.set_index(...)用作索引。
在其他情况下,我需要重置该索引以保留日期时间列。现在我正在寻找一种方法来检查数据框是否具有默认索引。我试过这个,但这并不适用于所有情况:
if df.index.name is not None:
df.reset_index(inplace=True)
Run Code Online (Sandbox Code Playgroud)
我可以测试索引是否为 datetime 类型,但我真的想知道是否有像df.is_index_set()这样的通用方法。有什么建议吗?
在我的场景中,我正在使用 PubSub 安排任务。这是多达 2.000 条 PubSub 消息,这些消息由在 Google Compute Engine 内的 Docker 容器内运行的 Python 脚本使用。该脚本使用 PubSub 消息。
每条消息的处理时间约为 30 秒到 5 分钟。因此,确认截止时间为 600 秒(10 分钟)。
from google.cloud import pubsub_v1
from google.cloud.pubsub_v1.subscriber.message import Message
def handle_message(message: Message):
# do your stuff here (max. 600sec)
message.ack()
return
def receive_messages(project, subscription_name):
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(project, subscription_name)
flow_control = pubsub_v1.types.FlowControl(max_messages=5)
subscription = subscriber.subscribe(subscription_path, flow_control=flow_control)
future = subscription.open(handle_message)
# Blocks the thread while messages are coming in through the stream. Any
# exceptions …Run Code Online (Sandbox Code Playgroud) python google-compute-engine docker google-cloud-platform google-cloud-pubsub
我对 Google AppScript 很陌生,试图编写一个连接到自定义 REST API 的连接器。对于那个 API,我需要一个 API 密钥(或秘密),这是每个用户的。由于在脚本中以纯文本形式存储秘密并不是最好的主意,我想将它存储在Google PropertyService 中并从那里检索它。像这样:
var userProperties = PropertiesService.getUserProperties();
var apiKey = userProperties.getProperty('MY_SECRET')
Run Code Online (Sandbox Code Playgroud)
但我不明白的是,用户怎么能先存储密钥?我还没有找到任何用户(在本例中是我)可以查看或编辑属性的地方。然后我发现了这个很好的用户属性介绍,它在脚本容器中创建了一个菜单,允许用户手动输入机密。
const API_KEY = 'API_KEY';
var ui = SpreadsheetApp.getUi();
var userProperties = PropertiesService.getUserProperties();
function onOpen(){
ui.createMenu('API Keys')
.addItem('Set API Key', 'userPromptApiKey')
.addItem('Delete API Key', 'deleteApiKey')
.addToUi();
}
function userPromptApiKey(){
var userValue = ui.prompt('API Key ', ui.ButtonSet.OK);
// ToDo: add current key to the prompt
userProperties.setProperty(API_KEY, userValue.getResponseText());
}
function deleteApiKey(){
userProperties.deleteProperty(API_KEY)
}
Run Code Online (Sandbox Code Playgroud)
问题是,我的脚本没有绑定到任何容器(没有电子表格,没有文档)。相反,我想稍后在 Google DataStudio 中使用它。这就是为什么
SpreadsheetApp.getUi(); …Run Code Online (Sandbox Code Playgroud) 我确实有一个 JavaScript 代码片段,它遍历一组字段以查找特定属性并将它们添加到字典中。另外,请参阅此站点以获取另一个示例。
return this.getFields()
.reduce((mappings, field) => ({...mappings, [field.id]: field.name}), {});
Run Code Online (Sandbox Code Playgroud)
这工作得很好。但是我收到了三个点的 Eslint 代码样式解析错误。
意外的标记 ...
关于这个的三个问题。
如何在保持代码简短的同时更改我的代码以避免解析错误?
我应该针对这个错误禁用 ESLint 检查吗?
...符号的名称是什么?
我的解决方法如下。但我更愿意保留原始版本。
return this.getFields()
.reduce(function(mappings, field) {
mappings[field.id] = field.name;
}, {});
Run Code Online (Sandbox Code Playgroud) python ×6
android ×2
apache-spark ×2
java ×2
javascript ×2
api-key ×1
blobstore ×1
dataframe ×1
datetime ×1
docker ×1
eslint ×1
geospatial ×1
imageview ×1
kdtree ×1
numpy ×1
pandas ×1
properties ×1
pyspark ×1
python-3.x ×1
scipy ×1
spatial ×1
sql ×1
surfaceview ×1
user-input ×1