【问题标题】:Python - Transpose data in desired formatPython - 以所需格式转置数据
【发布时间】:2018-10-29 17:17:51
【问题描述】:

这里是 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)

【问题讨论】:

  • 请将所有相关代码作为格式化文本包含在您的问题中。
  • 即使您还不确定如何以编程方式从一个到另一个,您仍然可以实际创建(示例)输入和输出列表结构。它只需要具有代表性。这有助于我们进行测试并确保我们为您提供预期的输出。图片链接可能会过期,您的问题会变得毫无意义
  • 我根据您的建议在上面添加了代码。

标签: python excel transpose


【解决方案1】:

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

【讨论】:

  • 谢谢!我刚刚在上面输入了我的代码。但我不确定如何更改代码以完全复制输出文件。
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2021-01-01
    • 2021-04-25
    相关资源
    最近更新 更多