You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spark SQL:如何拼接两个单行列DataFrame并生成计算列

实现方法(基于Pandas)

嘿,这个需求用Pandas很容易搞定,我给你两种常用的方案,都能得到你想要的结果:

方案一:使用pd.concat横向拼接

首先先假设你的两个DataFrame是这样定义的(如果实际变量名不同,替换成你自己的就行):

import pandas as pd

df_women = pd.DataFrame({'women color': [14]})
df_men = pd.DataFrame({'men color': [11]})

接下来分两步完成:

  1. 横向拼接两个单行列的DataFrame,得到一行两列的结果
  2. 新增计算列women-men,用两列数值相减即可

完整代码如下:

import pandas as pd

# 定义原始DataFrame
df_women = pd.DataFrame({'women color': [14]})
df_men = pd.DataFrame({'men color': [11]})

# 横向拼接(axis=1表示按列合并)
combined_df = pd.concat([df_women, df_men], axis=1)

# 添加差值计算列
combined_df['women-men'] = combined_df['women color'] - combined_df['men color']

# 查看结果
print(combined_df)

方案二:使用join方法拼接

如果你习惯用join,也可以这么写,效果完全一样:

import pandas as pd

df_women = pd.DataFrame({'women color': [14]})
df_men = pd.DataFrame({'men color': [11]})

# 直接join两个DataFrame
combined_df = df_women.join(df_men)
# 计算差值列
combined_df['women-men'] = combined_df['women color'] - combined_df['men color']

print(combined_df)

运行任意一种方案,都会输出你期望的结果:

women color  men color  women-men
0           14         11          3

内容的提问来源于stack exchange,提问作者Javier Navarro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:49:28