Skip to main content
 首页 » 编程设计

python之使用 Pandas [Python] 编辑特定单元格

2025年04月02日14myhome

我在使用 Pandas 时遇到了问题,到处都看过,但认为我忽略了一些东西。

我有一个导入 pandas 的 csv 文件,其中有一个 ID 列和另一列我将称为第 2 列。我想: 1.给python输入一个ID。 2. 用 Pandas 在 ID 列中搜索此 ID,并在第 2 列的相邻单元格中输入 1。

import pandas 
 
csvfile = pandas.read_csv('document1.csv') 
 
#Convert everything to string for simplicity 
csvfile['ID'] = csvfile['ID'].astype(str) 
 
#Fill in all missing NaN 
csvfile = csvfile.fillna('missing') 
 
#looking for the row in which the ID '10099870.0' is in.  
indexid = csvfile.loc[csvfile['ID'] == '10099870.0'].index 
 
# Important part! I think this selects the column 2, row 'indexid' and replaces missing with 1.  
csvfile['Column 2'][indexid].replace('missing', '1') 

我知道这是一个简单的问题,但感谢您的帮助!

毛里西奥

请您参考如下方法:

这就是我要做的:

cond = csvfile.ID == '10099870.0' 
col = 'Column 2' 
csvfile.loc[cond, col] = csvfile.loc[cond, col].replace('missing', '1')