python - for if 循环根据条件进行分类
问题描述
我对python很陌生,曾经使用过R。为此,我将使用as.factor并根据数字进行分类。
早些时候,我试图使用 replace 和 .loc 函数,以便根据条件在新列中提供新的类别值,但它只会在我想做的事情上失败。
最终,我创建了以下非常简单的函数:
g['Category'] = ""
for i in g['NumFloorsGroup']:
if i == '0-9' or i == '10-19':
g['Category'] = 'LowFl'
elif i == '50~':
g['Category'] = 'HighFl'
else:
g['Category'] = 'NormalFl'
但是,当我运行该函数时,它仅返回“LowFl”并且不会更正其他部分。我觉得我错过了什么。
数据信息如下:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 596 entries, 128 to 595
Data columns (total 4 columns):
YearBuilt 596 non-null int64
NumFloorsGroup 596 non-null category
Count 596 non-null int64
Category 596 non-null object
dtypes: category(1), int64(2), object(1)
任何评论都会有所帮助!
bins = [0, 10, 20, 30, 40, 50, np.inf]
labels = ['0-9', '10-19', '20-29', '30-39', '40-49', '50~']
copy = original_data.copy()
copy['NumFloorsGroup'] = pd.cut(copy['NumFloors'], bins=bins, labels=labels, include_lowest=True)
g = (copy.groupby(['YearBuilt', 'NumFloorsGroup'])['YearBuilt']
.count()
.reset_index(name="Count")
.sort_values(by='Count', ascending=False))
以及只返回 LowFl 的部分
g['Category'] = ""
for i in g['NumFloorsGroup']:
if i == '0-9' or i == '10-19':
g['Category'] = 'LowFl'
elif i == '50~':
g['Category'] = 'HighFl'
else:
g['Category'] = 'NormalFl'
这会将所有类别返回为 LowFl
YearBuilt NumFloorsGroup Count Category
128 1920 0-9 90956 LowFl
171 1930 0-9 76659 LowFl
144 1925 0-9 70387 LowFl
237 1950 0-9 47237 LowFl
91 1910 0-9 46384 LowFl
解决方案
我建议cut
用新的 bins 和新的标签来改变函数,因为最好的方法是避免 pandas 中的循环,因为如果存在一些矢量化函数,速度会很慢:
df = pd.DataFrame({'Floors':[0,1,10,19,20,25,40, 70]})
bins = [0, 10, 20, 30, 40, 50, np.inf]
labels = ['0-9', '10-19', '20-29', '30-39', '40-49', '50~']
df['NumFloorsGroup'] = pd.cut(df['Floors'],
bins=bins,
labels=labels,
include_lowest=True)
df['Category'] = pd.cut(df['Floors'],
bins=[0, 19, 50, np.inf],
labels=['LowFl','NormalFl','HighFl'],
include_lowest=True)
print (df)
Floors NumFloorsGroup Category
0 0 0-9 LowFl
1 1 0-9 LowFl
2 10 0-9 LowFl
3 19 10-19 LowFl
4 20 10-19 NormalFl
5 25 20-29 NormalFl
6 40 30-39 NormalFl
7 70 50~ HighFl
或者使用map
with dictinary withfillna
替换不在 dict( NaN
s) 中的值NormalFl
:
d = { "0-9": 'LowFl', "10-19": 'LowFl',"50+": 'HighFl'}
df['Category'] = df['NumFloorsGroup'].map(d).fillna('NormalFl')
推荐阅读
- javascript - 尝试使用注入脚本访问 Netflix 镉播放器,不再有效
- r - 如何使用嵌套 For 循环在单个图表中绘制多条线?
- c# - 在 c# 中使用 Emgu 为图像中的每个像素应用 ArcCos 的最快方法是什么
- azure - Azure 自定义愿景 | 无法从任何浏览器显示项目 | 铬,IE,边缘,火狐
- python - 让 tmux windows 继承`activate`d anaconda 环境
- reactjs - 如何使用 reactjs 构建评论回复结构?
- c# - 从 MySQL 获取正确的酒店价格
- angular - 当我们在 Angular Material 数据表中过滤数据时如何保留列索引?
- sql-server - 用于在 SQL Server 的 HTML 中替换标记元素的正则表达式
- javascript - 无法循环类似数组的对象