在panda datafram中插入值

2024-05-15 05:18:59 发布

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

我有Excel表格里的数据。我想检查一个列值的范围,如果该值位于该范围(5000-15000),那么我想在另一列中插入值(正确或标志)。

我有三个栏目:城市,租金,状态。

我尝试了append和insert方法,但没有成功。 我该怎么做?

这是我的代码:

对于索引,df.iterrows()中的行:

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

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

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

显示此错误:

TypeError:append()缺少1个必需的位置参数:“other”

在列中逐行插入数据应该遵循什么过程?


Tags: 数据方法代码dfif标志状态excel
1条回答
网友
1楼 · 发布于 2024-05-15 05:18:59

我认为您可以使用^{}和由^{}创建的布尔掩码,并与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

使用^{}的另一个解决方案:

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,请使用^{},如果需要,请删除索引列addindex=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

相关问题 更多 >

    热门问题