python - 在 panda 数据框中插入值

标签 python excel pandas

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

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

我尝试过追加和插入方法,但没有用。 我该怎么做?

这是我的代码:

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

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

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

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

它显示此错误:

类型错误:append() 缺少 1 个必需的位置参数:“其他”

我应该遵循什么步骤在列中逐行插入数据?

最佳答案

我认为你可以使用numpy.where带有 between 创建的 bool 掩码并与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)

编辑:

对于多个掩码可以使用:

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

关于python - 在 panda 数据框中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44500136/

相关文章:

使用 pip 和 conda 安装的 Python 包重复

python - 如何使用 MediaWiki API 获取子子类别中的文章数量

python - 如何在 python 上使用自定义拆分创建新列

python - 忽略 'usecol' 参数中的缺失列

python - Pandas:如何通过以下方式连接数据帧?

python - 复杂的 pandas 合并操作

python - 使用 python 从网站上抓取 socket.io 数据

vba - 从多单元格区域获取格式化值

python - 当每个值都是字典时将数据框保存到 Excel

excel - 在 B 列中为 A 列中的相同值选择最小值 excel?