这个需求人看起来不难,但并不好实现,用for循环难免效率太低,下面代码中逐步去生成每一列:
import pandas as pd
from itertools import chain
df1 = pd.DataFrame({"cond1":[84,94], "cond2":[74,6], "cond3":[27,31]}, index=["emp1", "emp2"])
df1_line_num = len(df1)
# 获取行列索引
df1_index = df1.index.tolist()
df1_columns = df1.columns.tolist()
# 构造 Employee 列
Employee = [[item] * len(df1_columns) for item in df1_index]
Employee = list(chain(*Employee)) # 先生成再拍平
# 构造 Condition 列
Condition = df1_columns * len(df1_index)
# 构造 Score 列
Score = df1.values.reshape((-1,)).tolist()
# 生成表2,并大写首字母
df2 = pd.DataFrame({"Employee": Employee, "Condition":Condition, "Score":Score})
df2["Employee"] = df2["Employee"].map(lambda x: x[0].upper()+x[1:])
df2["Condition"] = df2["Condition"].map(lambda x: x[0].upper()+x[1:])
print(df2)
如果有更好的实现欢迎交流哦,希望能帮到你 ^_^