如果一个数据帧列与另一个数据帧列匹配,则将该列中包含的匹配字符串置零

2024-04-18 09:39:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要做一个脚本,读取一个CSV和删除字符,出现在另一个单元格。即:

example

在第4行的“calle”列中,出现“28011”,它出现在“cod\u postal”列中。我需要从“calle”列中删除“28011”,但保持其余部分不变

我尝试了一些简单的脚本和研究,但我不能达到我需要的。你知道吗

编辑:是的,图像是一个例子,我有一个完整的2千行CSV

EDIT2:我试过这样的方法,但没能成功。。你知道吗

#-*-coding: latin1 -*-
import csv
import pandas

with open ('C:/trabajos/dani_cliente.csv') as csvfile:
    readcsv = csv.reader (csvfile, delimiter = ';')
    for row in readcsv:
        df ['cod_postal'] = np.where(df["cod_postal"]) < threshold, 
0,alt_value)
        print (row)    

编辑3:也尝试这个,可以得到工作,但只为指定的字符,我将需要在CSV的每一个“邮政编码”

#-*-coding: latin1 -*-

with open("C:/trabajos/extraccion_copia2.csv", 'r') as infile, \
     open("C:/trabajos/dani_cliente.test.csv", 'w') as outfile:


   # for row in infile
    #readcsv = csv.reader(infile, delimiter=';')
    data = infile.read()
    data = data.replace("28011", " ")
    outfile.write(data)

但是使用完整的CSV而不是示例CSV,我得到以下错误

回溯(最近一次呼叫): 文件“C:/Users/dalonso/PycharmProjects/untitled/开关测试.py“,第18行,in 数据=填充阅读() 文件“C:\Users\dalonso\AppData\Local\Programs\Python37\lib\encodings\cp1252.py”,第23行,解码 返回codecs.charmap\u解码(输入,自我错误,解码表)[0] UnicodeDecodeError:“charmap”编解码器无法解码位置577860中的字节0x90:字符映射到未定义


Tags: csvin脚本dataasopen解码字符
1条回答
网友
1楼 · 发布于 2024-04-18 09:39:24

我想我理解这个问题。。。如果它只是一个值,您可以简单地使用

df.loc[4,'cod_postal'] = 0
#if you want, can use NaN, but suggest just keeping 0. 

或者

df['cod_postal].iloc[4] = 0

如果有具体的指导方针,请使用np.哪里()或警察局哪里()

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html

np.where(condition, true_val, false_val) 
np.where(condition, true_val) # or if you want untouched in else condition

df['cod_postal'] = np.where(df["cod_postal"] < threshold, 0, alt_value)

下次提问时,请在问题中输入数据帧/代码

相关问题 更多 >