Fillna 通过使用创建的函数关联多个列
Fillna by relating multiple columns using a created function
我在数据框中有 3 列。
houses = ["house 1", "house 2", "house 3", "house 4", "house 5", "house 6", "house 7", "house 8", "house 9"]
room = ["厨房", "浴室", "卧室"]
m2 = [8.4.7, NaN, NaN, NaN, 6.3.7]。
我想要做的是用我设置的模式填充空白,这将是:
如果房间列为厨房,则m2为5。如果房间列为浴室,则m2为2。如果房间列为卧室,m2为4。
Input:
houses room m2
0 house 1 Kitchen 8
1 house 2 Bathroom 4
2 house 3 Bedroom 7
3 house 4 Kitchen NaN
4 house 5 Bathroom NaN
5 house 6 Bedroom NaN
6 house 7 Kitchen 6
7 house 8 Bathroom 3
8 house 9 Bedroom 7
Tried df.loc[(df["m2"].isnull() & df["room"] == "Kitchen"), "m2"] == 5
df.loc [(df ["m2"]. isnull () & df ["room"] == "Bathroom"), "m2"] == 2
df.loc [(df ["m2"]. isnull () & df ["room"] == "Bedroom"), "m2"] == 4
but it did not work.
FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison
Expected output:
houses room m2
0 house 1 Kitchen 8
1 house 2 Bathroom 4
2 house 3 Bedroom 7
3 house 4 Kitchen 5
4 house 5 Bathroom 2
5 house 6 Bedroom 4
6 house 7 Kitchen 6
7 house 8 Bathroom 3
8 house 9 Bedroom 7
df['m2'] = df['m2'].fillna(
df['room'].map({'Kitchen': 5, 'Bathroom': 2, 'Bedroom': 4})
).astype(int)
df['m2'] = np.where(
df['m2'].isna(),
df['room'].replace({'Kitchen': 5, 'Bathroom': 2, 'Bedroom': 4}),
df['m2']
).astype(int)
houses room m2
0 house 1 Kitchen 8
1 house 2 Bathroom 4
2 house 3 Bedroom 7
3 house 4 Kitchen 5
4 house 5 Bathroom 2
5 house 6 Bedroom 4
6 house 7 Kitchen 6
7 house 8 Bathroom 3
8 house 9 Bedroom 7
我在数据框中有 3 列。 houses = ["house 1", "house 2", "house 3", "house 4", "house 5", "house 6", "house 7", "house 8", "house 9"] room = ["厨房", "浴室", "卧室"] m2 = [8.4.7, NaN, NaN, NaN, 6.3.7]。 我想要做的是用我设置的模式填充空白,这将是: 如果房间列为厨房,则m2为5。如果房间列为浴室,则m2为2。如果房间列为卧室,m2为4。
Input:
houses room m2
0 house 1 Kitchen 8
1 house 2 Bathroom 4
2 house 3 Bedroom 7
3 house 4 Kitchen NaN
4 house 5 Bathroom NaN
5 house 6 Bedroom NaN
6 house 7 Kitchen 6
7 house 8 Bathroom 3
8 house 9 Bedroom 7
Tried df.loc[(df["m2"].isnull() & df["room"] == "Kitchen"), "m2"] == 5
df.loc [(df ["m2"]. isnull () & df ["room"] == "Bathroom"), "m2"] == 2
df.loc [(df ["m2"]. isnull () & df ["room"] == "Bedroom"), "m2"] == 4
but it did not work.
FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison
Expected output:
houses room m2
0 house 1 Kitchen 8
1 house 2 Bathroom 4
2 house 3 Bedroom 7
3 house 4 Kitchen 5
4 house 5 Bathroom 2
5 house 6 Bedroom 4
6 house 7 Kitchen 6
7 house 8 Bathroom 3
8 house 9 Bedroom 7
df['m2'] = df['m2'].fillna(
df['room'].map({'Kitchen': 5, 'Bathroom': 2, 'Bedroom': 4})
).astype(int)
df['m2'] = np.where(
df['m2'].isna(),
df['room'].replace({'Kitchen': 5, 'Bathroom': 2, 'Bedroom': 4}),
df['m2']
).astype(int)
houses room m2
0 house 1 Kitchen 8
1 house 2 Bathroom 4
2 house 3 Bedroom 7
3 house 4 Kitchen 5
4 house 5 Bathroom 2
5 house 6 Bedroom 4
6 house 7 Kitchen 6
7 house 8 Bathroom 3
8 house 9 Bedroom 7