df.select(df.col2 == df.col3).show()把结果添加到新列中
时间: 2024-01-22 21:19:54 浏览: 25
可以使用 `withColumn` 方法来添加结果到新列中,例如:
```python
from pyspark.sql.functions import when
df = df.withColumn("new_col", when(df.col2 == df.col3, "True").otherwise("False"))
df.show()
```
这将会在 `df` 中添加一个名为 `new_col` 的新列,其中包含 `col2` 等于 `col3` 的行的值为 `True`,否则为 `False`。你可以根据需要修改 `when` 和 `otherwise` 表达式来设置新列的值。
相关问题
df.select(df.col2 == df.col3).show()
这是一个 PySpark DataFrame 的操作,意思是选取 DataFrame 中 col2 和 col3 相等的行并展示出来。具体解释如下:
- df 是一个 PySpark DataFrame 对象;
- select() 方法用于选取满足条件的行;
- df.col2 和 df.col3 分别表示 DataFrame 中的两列;
- == 表示判断两个值是否相等;
- show() 方法用于展示选取后的结果。
转化为Python操作数据库的代码 new_b_df.withColumn("score", new_b_df['stars'] * 100 + new_b_df['review_count']) \ .where(new_b_df['is_open'] == 1) \ .select(col('name'), col('score')) \ .orderBy(col('score').desc()).show(1500, truncate=False)
以下是使用Python操作数据库的代码示例:
```python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
# 创建SparkSession对象
spark = SparkSession.builder.appName('example').getOrCreate()
# 从数据库中读取数据
df = spark.read.format('jdbc').options(
url='jdbc:mysql://localhost:3306/example',
driver='com.mysql.jdbc.Driver',
dbtable='business',
user='root',
password='123456'
).load()
# 对数据进行处理
new_b_df = df.withColumn("score", df['stars'] * 100 + df['review_count']) \
.where(df['is_open'] == 1) \
.select(col('name'), col('score')) \
.orderBy(col('score').desc())
# 将结果保存到数据库中
new_b_df.write.format('jdbc').options(
url='jdbc:mysql://localhost:3306/example',
driver='com.mysql.jdbc.Driver',
dbtable='result',
user='root',
password='123456'
).mode('overwrite').save()
```
需要注意的是,此示例代码仅供参考,具体实现方式可能因数据库类型、版本等因素而有所不同。