慕沐林林
没有示例 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, numpyimport pandas as pdimport numpy as np# Sample dfd = {'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 DataFramedf['Rooms'] = np.array(bedrooms)两种方式都会在名为“房间”的新列中显示结果 (0/1)。如果我没有正确猜测您的问题,请告诉我。祝你好运!