我对python还很陌生,以前经常使用Ras.系数并根据数字进行分类。你知道吗
早些时候,我尝试使用replace和.loc函数,以便根据条件在新列中提供一个新的category值,但它只会在我想做的事情上失败。你知道吗
最终我创建了以下非常简单的函数:
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
解决方案不起作用的原因是没有迭代数据帧。因此,要更正您的解决方案,与其直接将其分配给列,不如将值附加到列表中,然后稍后再将列表分配给数据帧。你知道吗
我建议将^{} 函数更改为新的bin和新的标签,因为最好的方法是避免pandas中的循环,因为如果存在一些向量化函数,则速度较慢:
或者使用^{} 和dictionary with ^{} 替换dict(
NaN
s)中没有的值,替换为NormalFl
:你可以试试这个:
相关问题 更多 >
编程相关推荐