简体   繁体   English

如何使用 pandas 数据框将数据框的每一列值添加到一张一张的新工作表中

[英]How to add each column of a data frame values in one by one new sheets using pandas data frame

I am new to python pandas and have some doubt.I want to store each column of the data frame in each new sheet in excel.我是 python pandas 的新手,并且有一些疑问。我想将数据框的每一列存储在 excel 的每个新工作表中。

Can anybody help me in implementing that.任何人都可以帮助我实现这一点。 I am putting code snippet as below for your reference.我将代码片段如下供您参考。

df.columns

Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')

for i in df.columns:
    print(df[i])
    with pd.ExcelWriter('output1.xlsx') as writer:  
        df.to_excel(writer, sheet_name='Sheet'+i+')

This should work:这应该有效:

import pandas as pd

# created a dummy row in a new dataframe as per the column list you shared
df2 = pd.DataFrame(['Dummy_PassengerId1', 'Dummy_Survived1', 'Dummy_Pclass1', 'Dummy_Name1', 'Dummy_Sex1', 'Dummy_Age1', 'Dummy_SibSp1',
       'Dummy_Parch1', 'Dummy_Ticket1', 'Dummy_Fare1', 'Dummy_Cabin1', 'Dummy_Embarked1']).T

# appended the appropriate headers to the dataframe
df2.columns = ['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked']

The above two steps were just to create a dummy dataframe with one row and required header.以上两个步骤只是创建一个虚拟 dataframe 一行,需要 header。 Its the line below that will meet your requirement (as I understood it): 'write each column of the dataframe to a new worksheet in the excel'.它下面的行将满足您的要求(据我了解):“将 dataframe 的每一列写入 excel 中的新工作表”。 Hope this clarifies.希望这可以澄清。

with pd.ExcelWriter('output1.xlsx') as writer:
    for col in df2.columns:      
        df2[col].to_excel(writer, sheet_name='Sheet_'+col)

The problem is you're not slicing your dataframe at each point.问题是你没有在每一点切割你的 dataframe 。

use:利用:

with pd.ExcelWriter('output.xlsx') as writer:
    for number,each_col in enumerate(df.columns,1):
        df[[each_col]].to_excel(writer,f'Sheet{number}',index=False)

or if you want the shetname to be the column name.或者,如果您希望 shetname 成为列名。

with pd.ExcelWriter('output.xlsx') as writer:
    for each_col in df.columns:
        df[[each_col]].to_excel(writer,f'Sheet{each_col}',index=False)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM