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

如何将多CSV列中特定值归集到新列并解决长度匹配错误?

房产数据CSV列归集处理解决方案

问题说明

现有25列CSV数据存储住宅单元特征(如空调、停车位等),需将所有列中值为Air Conditioned的内容归集到新列AC LIST,其余位置填充null(每行最多仅存在一个Air Conditioned记录)。

单列处理可行代码

column_1=(df['CSV_Col1_Name'])
AC_list=[]

for row in column_1:
    if row == 'Air Conditioned':
        AC_list.append(row)
    else:
        null=('null')
        AC_list.append(null)

df['AC LIST'] = np.array(AC_list)
df.to_csv("My_Data.csv",index=False) #CSV file already indexed

该代码可生成符合要求的新列,内容为null和Air Conditioned交替。

多列处理的错误及原因

处理剩余24列时尝试以下代码:

column_2=(df['CSV_Col2_Name'])
AC_list=[]

for row in column_2:
    if row == 'Air Conditioned':
        AC_list.append(row)
    else:
       continue

df['AC LIST'] = np.array(AC_list)

运行报错:

ValueError: Length of values (258) does not match length of index (229)

原因是仅在匹配到Air Conditioned时向列表添加元素,不匹配时跳过,导致AC_list长度与DataFrame行索引数量不匹配。

解决方法

方法1:逐行遍历所有目标列

遍历每一行,检查25列中是否存在Air Conditioned,存在则填入新列,否则填null:

import numpy as np
import pandas as pd

# 替换为你的25列实际列名列表
target_cols = ['CSV_Col1_Name', 'CSV_Col2_Name', ..., 'CSV_Col25_Name']

AC_list = []
for _, row in df[target_cols].iterrows():
    if 'Air Conditioned' in row.values:
        AC_list.append('Air Conditioned')
    else:
        AC_list.append('null')

df['AC LIST'] = np.array(AC_list)
df.to_csv("My_Data.csv", index=False)

方法2:Pandas内置函数高效处理

利用Pandas的向量化操作简化代码,效率更高:

import numpy as np
import pandas as pd

target_cols = ['CSV_Col1_Name', 'CSV_Col2_Name', ..., 'CSV_Col25_Name']

# 检查每行是否在目标列中有Air Conditioned,生成新列
df['AC LIST'] = np.where(
    df[target_cols].eq('Air Conditioned').any(axis=1),
    'Air Conditioned',
    'null'
)

df.to_csv("My_Data.csv", index=False)
  • df[target_cols].eq('Air Conditioned'):生成布尔值矩阵,标记每个单元格是否为目标值
  • .any(axis=1):判断每行是否存在至少一个True(即存在Air Conditioned)
  • np.where:根据条件批量替换值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:01:06