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

如何用Pandas导入列规范的CSV文件并拆分行列?

从CSV导入的数据生成新行和列的方法

假设你用Pandas处理CSV数据,下面是几种常见的生成新行/列的实操方法:

生成新列

1. 基于现有列计算生成

如果新列是现有列的运算结果,直接用列操作即可:

import pandas as pd

# 常规导入CSV
df = pd.read_csv('your_data.csv')

# 示例:两列相加生成新列
df['sum_col'] = df['col1'] + df['col2']

# 复杂逻辑用apply处理
df['logic_col'] = df.apply(lambda row: row['col1'] * 3 if row['col2'] > 50 else row['col1'] / 2, axis=1)

2. 添加固定值/序列列

如果新列是固定内容或递增序列:

# 添加固定值列
df['status'] = 'processed'

# 添加自增序号列
df['id'] = range(1, len(df)+1)

生成新行

1. 添加单条新行

构造和原DataFrame列匹配的字典,用concat添加:

new_row = {'col1': 123, 'col2': 456, 'sum_col': 579}
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)

2. 批量添加多行

从列表或另一个数据集批量导入新行:

new_rows = [
    {'col1': 789, 'col2': 101},
    {'col1': 202, 'col2': 303}
]
df = pd.concat([df, pd.DataFrame(new_rows)], ignore_index=True)

3. 拆分现有行生成新行

如果某列包含可拆分的内容(比如逗号分隔的字符串),可以拆分成多行:

# 假设col3是逗号分隔的字符串,拆分后生成新行
df = df.assign(col3=df['col3'].str.split(',')).explode('col3')

如果你的需求是特定规则(比如根据某列的条件拆分、生成聚合行等),可以补充截图里的具体数据结构或规则,这样能给出更精准的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:35:39