根据表状态扩展功能是错误的,因为您不能用其他数据重复它。如果你想以这种方式创建特征,你应该使用一个能记住特征结构的构造函数。由于您没有提供数据示例,因此主要思想是如何制作构造函数:
import pandas as pd
data = pd.DataFrame([['Missouri', 'center', 'Jan', 55, 11],
['Kansas', 'center', 'Mar', 54, 31],
['Georgia', 'east', 'Jan', 37, 18]],
columns=('state', 'pos', 'month', 'High Temp', 'Low Temp'))
test = pd.DataFrame([['Missouri', 'center', 'Feb', 44, 23],
['Missouri', 'center', 'Mar', 55, 33]],
columns=('state', 'pos', 'month', 'High Temp', 'Low Temp'))
class DummyColumns():
def __init__(self, data):
# Columns constructor
self.empty = pd.DataFrame(columns=(list(data.columns) +
list(data.state.unique()) +
list(data.pos.unique()) +
['Winter', 'Not winter']))
def __call__(self, data):
# Initializing with zeros
self.df = pd.DataFrame(data=0, columns=self.empty.columns, index=data.index)
for row in data.itertuples():
self.df.loc[row.Index, :5] = row[1:]
self.df.loc[row.Index, row.state] = 1
self.df.loc[row.Index, row.pos] = 1
if row.month in ['Dec', 'Jan', 'Feb']:
self.df.loc[row.Index, 'Winter'] = 1
else:
self.df.loc[row.Index, 'Not winter'] = 1
return self.df
add_dummy = DummyColumns(data)
dummy_test = add_dummy(test)
print dummy_test
state pos month High Temp Low Temp Missouri Kansas Georgia \
0 Missouri center Feb 44 23 1 0 0
1 Missouri center Mar 55 33 1 0 0
center east Winter Not winter
0 1 0 1 0
1 1 0 0 1