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

如何在同一DataFrame中将目标相关列追加为新行

问题:如何在同一DataFrame中,将target_mmsi、target_lat、target_lon连同对应datetime作为新行追加到原数据中?

复现数据

data = {
    'datetime': ['2019-01-01 08:03:00', '2019-01-01 08:04:00', '2019-01-01 08:04:00'],
    'own_mmsi': [236385000, 236385000, 244013009],
    'target_mmsi': [244013009, 244013009, 236385000],
    'own_lat': [59.330711, 59.330400, 59.327970],
    'own_lon': [10.515833, 10.514336, 10.515833],
    'target_lat': [59.327478, 59.327970, 59.330400],
    'target_lon': [10.515475, 10.515833, 10.514336],
}

需求说明

将每条数据中的target_mmsi、target_lat、target_lon与对应datetime作为新行添加到整个DataFrame中,最终输出结构如下(展示前2行):

datetimeown_mmsilatlon
2019-01-01 08:03:0023638500059.33071110.515833
2019-01-01 08:03:0024401300959.32747810.515475

尝试过的无效代码

melted_df = pd.melt(
    df,
    id_vars=['datetime', 'own_mmsi', 'CRI'],
    value_vars=['target_mmsi', 'target_lat', 'target_lon'],
    var_name='attribute',
    value_name='value'
)

# Pivot the melted DataFrame to reshape it
reshaped_df = melted_df.pivot_table(
    index=['datetime', 'own_mmsi', 'CRI'],
    columns='attribute',
    values='value',
    aggfunc='first'
).reset_index()

# Rename columns for clarity
reshaped_df.columns.name = None  # Remove the name of the columns index
reshaped_df = reshaped_df.rename(columns={'target_mmsi': 'own_target_mmsi', 'target_lat': 'own_target_lat', 'target_lon': 'own_target_lon'})

print(reshaped_df)

正确实现方法

核心逻辑是拆分原数据为自有船舶数据集和目标船舶数据集,统一两者的列名后纵向合并:

  1. 从原数据中提取自有船舶相关字段,将own_lat、own_lon重命名为lat、lon
  2. 提取目标船舶相关字段,将target_mmsi替换为own_mmsi,同时重命名target_lat、target_lon为lat、lon
  3. 使用pd.concat()合并两个数据集,重置索引

完整代码

import pandas as pd

# 构建原始DataFrame
df = pd.DataFrame(data)

# 处理自有船舶数据
own_vessels = df[['datetime', 'own_mmsi', 'own_lat', 'own_lon']].rename(
    columns={'own_lat': 'lat', 'own_lon': 'lon'}
)

# 处理目标船舶数据
target_vessels = df[['datetime', 'target_mmsi', 'target_lat', 'target_lon']].rename(
    columns={'target_mmsi': 'own_mmsi', 'target_lat': 'lat', 'target_lon': 'lon'}
)

# 合并并重置索引
final_df = pd.concat([own_vessels, target_vessels], ignore_index=True)

# 输出结果验证
print(final_df)

输出结果

datetimeown_mmsilatlon
2019-01-01 08:03:0023638500059.33071110.515833
2019-01-01 08:04:0023638500059.33040010.514336
2019-01-01 08:04:0024401300959.32797010.515833
2019-01-01 08:03:0024401300959.32747810.515475
2019-01-01 08:04:0024401300959.32797010.515833
2019-01-01 08:04:0023638500059.33040010.514336

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 16:52:17