我有一个PySpark DataFrame,df1,看起来像:
CustomerID CustomerValue
12 .17
14 .15
14 .25
17 .50
17 .01
17 .35
Run Code Online (Sandbox Code Playgroud)
我有第二个PySpark DataFrame,df2,它是由CustomerID分组并由sum函数聚合的df1.它看起来像这样:
CustomerID CustomerValueSum
12 .17
14 .40
17 .86
Run Code Online (Sandbox Code Playgroud)
我想为df1添加第三列,即df1 ['CustomerValue']除以df2 ['CustomerValueSum'],用于相同的CustomerID.这看起来像:
CustomerID CustomerValue NormalizedCustomerValue
12 .17 1.00
14 .15 .38
14 .25 .62
17 .50 .58
17 .01 .01
17 .35 .41
Run Code Online (Sandbox Code Playgroud)
换句话说,我正在尝试将此Python/Pandas代码转换为PySpark:
normalized_list = []
for idx, row in df1.iterrows():
(
normalized_list
.append(
row.CustomerValue / df2[df2.CustomerID == row.CustomerID].CustomerValueSum
)
)
df1['NormalizedCustomerValue'] = [val.values[0] for val in normalized_list]
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我正在尝试创建一个 JSON 行的数据文件,以便与 google cloud AI 平台对在线预测的要求兼容。
现在我有每个数据点的字典列表。它看起来像这样:
data = [{'values': [0,1,0], 'key': 0}, {'values': [1,1,0], 'key': 1}]
Run Code Online (Sandbox Code Playgroud)
我使用以下代码将此数据导出到data.json:
import json
json_filepath = "data.json"
with open(json_filepath, 'w') as f:
json.dump(data, f)
Run Code Online (Sandbox Code Playgroud)
问题是,这个data.json文件看起来和我的数据完全一样(即字典列表)。如何使这个data.json文件成为列表中每个字典的换行分隔集合?换句话说,我怎样才能让它看起来像这样:
{'values': [0,1,0], 'key': 0}
{'values': [1,1,0], 'key': 1}
Run Code Online (Sandbox Code Playgroud) 我的代码看起来像这样:
name = Joe
print "Hello", name, "!"
Run Code Online (Sandbox Code Playgroud)
我的输出看起来像:
Hello Joe !
Run Code Online (Sandbox Code Playgroud)
如何删除之间的空间Joe和!?
我正在 Python 3.6.6 中创建一个字典字符串(稍后添加到 .txt 文件中)。
当我对字典的字符串进行硬编码时,我没有遇到任何问题:
my_string = '{"source": "s3://some_s3_bucket/random_filename.csv"} \n'
print(my_string)
Run Code Online (Sandbox Code Playgroud)
输出
{“源”:“s3://some_s3_bucket/random_filename.csv”}
然而,当我尝试用硬编码文件路径替换变量时,Python 似乎开始假设“source”是我想要替换的变量:
bucket = "some_s3_bucket"
filename = "random_filename.csv"
my_new_string = '{"source": "s3://{0}/{1}"} \n'.format(bucket, filename)
print(my_new_string)
Run Code Online (Sandbox Code Playgroud)
输出
模块中的 KeyError Traceback(最近一次调用最后一次)
--> 1 my_new_string = '{"source": "s3://{0}/{1}"} \n'.format(bucket, filename)
2 print(my_new_string )关键错误:'“来源”'
我应该如何格式化该字符串以便 Python 正确读取我的存储桶和文件名变量?