根据另一列的条件填充空值 (pandas)
Fill null values based on condition for another column (pandas)
我正在尝试在我的数据集中填充空值。描述栏有公寓类型。对于单间公寓,我尝试填写为 0 间卧室,而对于房间,我尝试填写为 1 间卧室。
我试过了
df.loc[df['Description'] == 'Studio', 'Bedrooms'] = df['Bedrooms'].fillna(0)
df.loc[df['Description'] == 'Rooms', 'Bedrooms'] = df['Bedrooms'].fillna(1)
但它不起作用。有人有什么建议吗?
没有示例 DataFrame,我不得不猜测你到底想要什么,希望我是对的。
您可以使用简单的 lambda 函数:
# Import pandas, numpy
import pandas as pd
import numpy as np
# Sample df
d = {'Desc': ['Studio', 'Rooms', 'Studio', 'Studio', 'Studio', 'Rooms','Rooms','Rooms','Studio', 'Rooms']}
df = pd.DataFrame(data=d)
df['Rooms'] = np.nan
# Lambda function
df['Rooms'] = df.apply(
lambda row: 0 if row['Desc'] == 'Studio' else 1,
axis=1
)
或者使用 list + for 循环并向你的 df 添加新列。
# Import pandas, numpy
import pandas as pd
import numpy as np
# Sample df
d = {'Desc': ['Studio', 'Rooms', 'Studio', 'Studio', 'Studio', 'Rooms','Rooms','Rooms','Studio', 'Rooms']}
df = pd.DataFrame(data=d)
# Create empty list for bedroom numbers.
bedrooms = []
# Fill the list with 0/1 base on your Studio/Rooms option.
for i in range(0,len(df.index)):
if df['Desc'].loc[i].lower() == 'studio':
bedrooms.append(0)
else:
bedrooms.append(1)
# Add new column to your DataFrame
df['Rooms'] = np.array(bedrooms)
这两种方式都会在名为 'Rooms' 的新列中显示结果 (0/1)。
如果我没有猜对你的问题,请告诉我。
祝你好运!
我正在尝试在我的数据集中填充空值。描述栏有公寓类型。对于单间公寓,我尝试填写为 0 间卧室,而对于房间,我尝试填写为 1 间卧室。
我试过了
df.loc[df['Description'] == 'Studio', 'Bedrooms'] = df['Bedrooms'].fillna(0)
df.loc[df['Description'] == 'Rooms', 'Bedrooms'] = df['Bedrooms'].fillna(1)
但它不起作用。有人有什么建议吗?
没有示例 DataFrame,我不得不猜测你到底想要什么,希望我是对的。
您可以使用简单的 lambda 函数:
# Import pandas, numpy
import pandas as pd
import numpy as np
# Sample df
d = {'Desc': ['Studio', 'Rooms', 'Studio', 'Studio', 'Studio', 'Rooms','Rooms','Rooms','Studio', 'Rooms']}
df = pd.DataFrame(data=d)
df['Rooms'] = np.nan
# Lambda function
df['Rooms'] = df.apply(
lambda row: 0 if row['Desc'] == 'Studio' else 1,
axis=1
)
或者使用 list + for 循环并向你的 df 添加新列。
# Import pandas, numpy
import pandas as pd
import numpy as np
# Sample df
d = {'Desc': ['Studio', 'Rooms', 'Studio', 'Studio', 'Studio', 'Rooms','Rooms','Rooms','Studio', 'Rooms']}
df = pd.DataFrame(data=d)
# Create empty list for bedroom numbers.
bedrooms = []
# Fill the list with 0/1 base on your Studio/Rooms option.
for i in range(0,len(df.index)):
if df['Desc'].loc[i].lower() == 'studio':
bedrooms.append(0)
else:
bedrooms.append(1)
# Add new column to your DataFrame
df['Rooms'] = np.array(bedrooms)
这两种方式都会在名为 'Rooms' 的新列中显示结果 (0/1)。
如果我没有猜对你的问题,请告诉我。
祝你好运!