Python-以所需格式转置数据

时间:2018-10-29 17:17:52

标签: python excel transpose

此处是Python新手。我能否知道如何将下面的给定数据转换为下面提到的所需格式?

源数据:

Source Data

输出数据必须类似于:

Output data

请告知。

到目前为止,我的代码:

# Transposing an excel file using python
import pandas as pd

# Location of the file
loc = ("C:\\Users\\user1\\Documents\\Python_Files\\data.xlsx")

# Reading the file
df=pd.read_excel("C:\\Users\\user1\\Documents\\Python_Files\\data.xlsx")

# Transposing the file
df.T.to_excel('C:\\Users\\user1\\Documents\\Python_Files\\data1.xlsx', index=False)

2 个答案:

答案 0 :(得分:0)

您可以尝试使用pandas库将pandas.read_csv read_csv documentation函数作为数据帧导入原始数据,然后使用pandas.DataFrame.transpose {{3}函数将数据帧转置}

答案 1 :(得分:0)

我自己找到了答案。仅供参考,代码如下:

import pandas as pd

# Location of the file
loc = "C:\\Users\\user1\\Documents\\Python_Files\\data.xlsx"

# Reading the file
df=pd.read_excel(loc)

#Transposing the file
out = df.pivot_table(values='H', index=['V','ED','D','F','SF','T'],columns=['SPH'], fill_value=0)
print(out)

out1 = pd.DataFrame(out).reset_index()
print(out1)

out2 = pd.DataFrame(out1.transpose()).reset_index()
print(out2)

out2.rename(columns={'SPH':-1}, inplace=True)
print(out2)

out2.rename(columns=lambda x: x+1, inplace=True)
print(out2)

out2.rename(columns={0:'Name'}, inplace=True)
print(out2)

#Save
out2.to_excel("C:\\Users\\user1\\Documents\\Python_Files\\data1.xlsx", index=False)