根据不同列中的空白单元格将文本输入到列中

2024-06-12 11:32:42 发布

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

这是我的密码:

    finalCSV = pd.read_csv('pathName') #Open new CSV
#create col for isMAP based on true or false
    finalCSV['isMap'] = np.where(finalCSV['MAP'] == finalCSV['productPrice'], 'True', 'False')
    finalCSV = finalCSV.sort_values(by = ['isMap'], ascending = True,) #Make it so the falses come out first

if finalCSV['productSKU'].isna().all():
     finalCSV['isMap'].str.replace('False' ,'N/A')
finalCSV.to_csv('pathName', index = False) #Close and overwrite CSV

这是我正在处理的csv文件的图像 enter image description here

我要做的是,如果“productSKU”中的相邻单元格为空,则在“isMap”列上输入文本N/A。但是,当我运行代码段时,excel文件将保留“FALSE”而不是“N/A”

编辑:这是我的CSV的链接

https://drive.google.com/file/d/10Xnw33SbYmEgPC-UUBjJvrDMf0XfVtdq/view?usp=sharing

一些额外的澄清

给出了前3列,productName、productOMS、productPrice、productSKU和productURL都是我在webscraper中获得的项目。isMap是我在这个程序中创建的一个列,然后用结果动态填充它

所以

if MAP == productPrice, isMap would return true
if MAP != productPrice isMap would return false

现在,如果我的webscraper无法获取产品SKU和/或productName,则意味着该产品在网站上不存在

if productSKU is NULL, isMap would return not available

这是数据帧头:

{'SKU': {0: 'FRC5131-WM-33', 275: 'KECOM-36', 276: 'DW-BS-24', 277: 'BS655N-48', 278: '8654WM-36'}, 

'MAP': {0: nan, 275: 779.95, 276: nan, 277: 1299.95, 278: 1295.95}, 


'productSKU': {0: nan, 275: nan, 276: nan, 277: nan, 278: nan}, 


'productPrice': {0: nan, 275: nan, 276: nan, 277: nan, 278: nan}, 


'productName': {0: nan, 275: nan, 276: nan, 277: nan, 278: nan}, 

'HOME DEPOT (OMSID)': {0: 312962522, 275: 206922074, 276: 308581002, 277: 312332575, 278: 309618527}, 

'productURL': {0: 'https://www.homedepot.com/p/312962522', 275: 'https://www.homedepot.com/p/206922074', 276: 'https://www.homedepot.com/p/308581002', 277: 'https://www.homedepot.com/p/312332575', 278: 'https://www.homedepot.com/p/309618527'}, 

'isMap': {0: 'False', 275: 'False', 276: 'False', 277: 'False', 278: 'False'}, 

'productOMS': {0: 312962522, 275: 206922074, 276: 308581002, 277: 312332575, 278: 309618527}}

Tags: csvhttpscomfalsemapifwwwnan
2条回答

如果其他人也有同样的问题,这就成功了

finalCSV['isMap'] = np.where( finalCSV['productSKU'].isna(), "Not Available", finalCSV['isMap'])

编辑:

对于您发布的CSV文件,finalCSV['productSKU'].isna().all()在第7行和第9行是False,在productSKU列中有值

手动删除这两个值会产生错误,因为 isMap列被自动检测为bool类型

另一件令人困惑的事情是,Pandas将字符串N/A解释为“非数字”值。。。!请参阅na_values下的文档here

我建议使用N/A以外的其他值作为结果值。:-)原始答案和下面的固定代码


解决办法似乎是:

finalCSV = pd.read_csv(pathName, dtype={'isMap': str}) #Open new CSV

is_na_index = finalCSV['isMap'][finalCSV['productSKU'].isna()].index

finalCSV.loc[is_na_index, 'isMap'] = finalCSV.loc[is_na_index, 'isMap'].replace('FALSE', 'Not Available')

finalCSV.to_csv(pathName, index = False) #Close and overwrite CSV

相关问题 更多 >