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

Python中如何基于条件向pandas DataFrame的列追加新行?

解决方案

你可以直接用pd.concat()实现行追加,该方法兼容目前所有pandas版本,不需要转置操作,不会改动原有数据结构:

完整可运行代码

import pandas as pd
# 你的原有示例数据
d = {'cat': ['man1','man', 'woman','woman'], 'age': [30, 40, 50,55]}
df = pd.DataFrame(data=d)

# 计算新增行的age数值
max_woman_age = df.loc[df['cat'] == 'woman', 'age'].max()
max_man_age = df.loc[df['cat'] == 'man', 'age'].max()
first_child_age = max_woman_age - max_man_age
sec_child_age = 10 # 可替换为你实际的计算逻辑

# 构造待追加的行数据
new_rows = pd.DataFrame([
    {'cat': 'first_child', 'age': first_child_age},
    {'cat': 'sec_child', 'age': sec_child_age}
])

# 追加到原有DataFrame末尾
df = pd.concat([df, new_rows], ignore_index=True)

print(df)

输出结果

cat  age
0        man1   30
1         man   40
2       woman   50
3       woman   55
4  first_child   15
5    sec_child   10

原有代码问题说明

  • 存在拼写错误:append误写为apend
  • DataFrame.append()方法已在pandas 1.4版本后弃用,不推荐继续使用,pd.concat()是官方推荐的替代方案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:54:01