我的房屋租金数据如下:
import pandas as pd
import numpy as np
data = {
"HouseName": ["A", "A", "B", "B", "B"],
"Type": ["OneRoom", "TwoRooms", "OneRoom", "TwoRooms", "ThreeRooms"],
"Jan_S": [1100, 1776, 1228, 1640, np.NaN],
"Feb_S": [1000, 1805, 1231, 1425, 1800],
"Mar_S": [1033, 1748, 1315, 1591, 2900],
"Jan_L": [1005, np.NaN, 1300, np.NaN, 7000]
}
df = pd.DataFrame.from_dict(data)
print(df)
HouseName Type Jan_S Feb_S Mar_S Jan_L
0 A OneRoom 1100.0 1000 1033 1005.0
1 A TwoRooms 1776.0 1805 1748 NaN
2 B OneRoom 1228.0 1231 1315 1300.0
3 B TwoRooms 1640.0 1425 1591 NaN
4 B ThreeRooms NaN 1800 2900 7000.0
我需要意识到两件事:首先,我想根据“ Jan_S”,“ Feb_S”,“ Mar_S”,“ Jan_L”列找到合理的1月租金。这里S和L表示两个不同的数据源,它们都可能具有异常值和nans,但是来自S的数据将优先作为一月份的最终价格。 其次,对于同一个HouseName,我需要检查并确保一个房间的价格低于两个房间,而两个房间的价格低于三个房间。 我的最终结果将如下所示:
HouseName Type Jan_S Feb_S Mar_S Jan_L
0 A OneRoom 1100.0 1000 1033 1005.0
1 A TwoRooms 1776.0 1805 1748 NaN
2 B OneRoom 1228.0 1231 1315 1300.0
3 B TwoRooms 1640.0 1425 1591 NaN
4 B ThreeRooms NaN 1800 2900 7000.0
Result(Jan)
0 1100
1 1776
2 1228
3 1640
4 1800
我的想法是检查Jan_S是否在Jan_L的0.95到1.05之间,如果是,将Jan_S作为最终结果,否则,继续检查Feb_S中的值作为Jan_S。
请分享您可能需要用Python处理此问题的所有想法。谢谢! 这里有一些参考资料可能会有所帮助。
Find nearest value from multiple columns and add to a new column in Python
Compare values under multiple conditions of one column in Python
Check if values in one column is in interval values of another column in Python
答案 0 :(得分:1)
您可以为此使用fillna。
如果要以选择列为条件,则需要弄清楚逻辑以过滤列以从中选择值。
我正在使用所有价格列的min()展示逻辑
# filter out the price columns
price_cols = df.columns[~df.columns.isin(['HouseName','Type', 'Jan_S'])]
# then figure out the logic to filter the columns you need and use fillna
# here with the min of all columns as example
df['Jan_S'] = df['Jan_S'].fillna(df[price_cols].apply(min, axis=1))