当我转置数据帧时,默认情况下标头被视为“索引”。但我希望它是一列而不是索引。我该如何实现?
import pandas as pd
dict = {'col-a': [97, 98, 99],
'col-b': [34, 35, 36],
'col-c': [24, 25, 26]}
df = pd.DataFrame(dict)
print(df.T)
0 1 2
col-a 97 98 99
col-b 34 35 36
col-c 24 25 26
所需的输出:
0 1 2 3
0 col-a 97 98 99
1 col-b 34 35 36
2 col-c 24 25 26
答案 0 :(得分:1)
尝试from sklearn.metrics import make_scorer
scorer = make_scorer(your_custom_score_func)
opt.fit(X_train, y_train, X_val, y_val, scoring=scorer)
和hypopt.GridSearch.fit()
:
T
或者:
reset_index
两个输出:
df=df.T.reset_index()
print(df)
如果关心列名,请将其添加到代码中:
df.T.reset_index(inplace=True)
print(df)
或者:
index 0 1 2
0 col-a 97 98 99
1 col-b 34 35 36
2 col-c 24 25 26
或者如果不知道列数:
df.columns=range(4)
或者:
it=iter(range(4))
df=df.rename(columns=lambda x: next(it))
所有输出:
df.columns=range(len(df.columns))
答案 1 :(得分:0)
使用reset_index
,然后设置默认列名称:
df1 = df.T.reset_index()
df1.columns = np.arange(len(df1.columns))
print (df1)
0 1 2 3
0 col-a 97 98 99
1 col-b 34 35 36
2 col-c 24 25 26
另一种解决方案:
print (df.rename_axis(0, axis=1).rename(lambda x: x + 1).T.reset_index())
#alternative
#print (df.T.rename_axis(0).rename(columns = lambda x: x + 1).reset_index())
0 1 2 3
0 col-a 97 98 99
1 col-b 34 35 36
2 col-c 24 25 26