在panda数据框中插入值

3

我有一个Excel工作表里面的数据。我想要检查一列的值是否在范围内(5000-15000),如果是,那么我就要在另一列中插入值(“Correct”或“Flag”)。

我有三列数据:城市、租金和状态。

我尝试了“append”和“insert”方法,但都没有成功。请问我该如何操作?

以下是我的代码:

for index, row in df.iterrows():

if row['city']=='mumbai':

    if 5000<= row['rent']<=15000:

        pd.DataFrame.append({'Status': 'Correct'})

它显示了以下错误:
TypeError:append()缺少1个必需的位置参数:'other'
为逐行插入数据行,请按照以下步骤进行操作:
1个回答

1
我认为您可以使用numpy.where,并结合由between创建的布尔掩码和与city比较的方式。
mask = (df['city']=='mumbai') & df['rent'].between(5000,15000)
df['status'] = np.where(mask, 'Correct', 'Uncorrect')

示例:

df = pd.DataFrame({'city':['mumbai','mumbai','mumbai', 'a'],
                   'rent':[1000,6000,10000,10000]})
mask = (df['city']=='mumbai') & df['rent'].between(5000,15000)
df['status'] = np.where(mask, 'Correct', 'Flag')
print (df)
     city   rent   status
0  mumbai   1000     Flag
1  mumbai   6000  Correct
2  mumbai  10000  Correct
3       a  10000     Flag

另一种使用 loc 的解决方案是:
mask = (df['city']=='mumbai') & df['rent'].between(5000,15000)
df['status'] = 'Flag'
df.loc[mask, 'status'] =  'Correct'
print (df)
     city   rent   status
0  mumbai   1000     Flag
1  mumbai   6000  Correct
2  mumbai  10000  Correct
3       a  10000     Flag

要将数据写入Excel,请使用to_excel,如果需要去除索引列,请添加index=False

df.to_excel('file.xlsx', index=False)

编辑:

对于多个mask,可以使用以下方法:

df = pd.DataFrame({'city':['Mumbai','Mumbai','Delhi', 'Delhi', 'Bangalore', 'Bangalore'],
                   'rent':[1000,6000,10000,1000,4000,5000]})
print (df)
        city   rent
0     Mumbai   1000
1     Mumbai   6000
2      Delhi  10000
3      Delhi   1000
4  Bangalore   4000
5  Bangalore   5000

m1 = (df['city']=='Mumbai') & df['rent'].between(5000,15000)
m2 = (df['city']=='Delhi') & df['rent'].between(1000,5000)
m3 = (df['city']=='Bangalore') & df['rent'].between(3000,5000)

m = m1 | m2 | m3
print (m)
0    False
1     True
2    False
3     True
4     True
5     True
dtype: bool

from functools import reduce
mList = [m1,m2,m3]
m = reduce(lambda x,y: x | y, mList)
print (m)
0    False
1     True
2    False
3     True
4     True
5     True
dtype: bool

print (df[m])
        city  rent
1     Mumbai  6000
3      Delhi  1000
4  Bangalore  4000
5  Bangalore  5000

它显示了正确的结果,但它没有将数据写入我的Excel表格。 - NILESH SUTHAR
它删除了我的工作表之前的数据。它只插入了一个状态列。请在这种情况下帮忙。 - NILESH SUTHAR
数据在 df 中不同吗?如果原始数据被相同的覆盖,只有新列被添加,那么会出现问题吗?你能再解释一下吗? - jezrael
实际上,我有一个包含50列的Excel文件,其中状态是其中一个空列。我想在现有文件中插入此列的值,但它会删除所有其他列。 - NILESH SUTHAR
很高兴能够帮忙。我总是尝试添加一些数据样本,这对于理解问题最有帮助。感谢您的接受! - jezrael
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接