简体   繁体   English

如何将电子表格中的第一行用作数据框列名,而不是0 1 2…等?

[英]How do I use my first row in my spreadsheet for my Dataframe column names instead of 0 1 2…etc?

I want my dataframe to display the first row names as my dataframe column name instead of numbering from 0 etc. How do I do this? 我希望我的数据框显示第一行名称作为数据框的列名称,而不是从0等开始编号。我该如何做?

I tried using pandas and openpyxl modules to turn my Excel spreadsheet into a dataframe. 我尝试使用pandas和openpyxl模块将Excel电子表格转换为数据框。

import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows

wb = load_workbook(filename='Budget1.xlsx')
print(wb.sheetnames)
sheet_ranges=wb['May 2019']
print(sheet_ranges['A3'].value)

ws=wb['May 2019']
df=pd.DataFrame(ws.values)
print(df) # This displays my dataframe.

I expect my column titles of my dataframe to display Date, Description, and Amount instead of 0, 1, 2. 我希望数据框的列标题显示日期,描述和金额,而不是0、1、2。

you can reset the columns to be the first row of your dataframe: 您可以将列重置为数据框的第一行:

df.columns = df.iloc[0, :]
df.drop(df.index[0], inplace=True)
df

在此处输入图片说明

After reading data dataframe using pandas you can separate first row then use that as column name: 使用熊猫读取数据框后,您可以分隔第一行,然后将其用作列名:

columnNames = df.iloc[0] 
df = df[1:] 
df.columns = columnNames

Or, you can directly read using pandas that will set first row as column name: 或者,您可以使用将第一行设置为列名的熊猫直接阅读:

excelDF = pd.ExcelFile('Budget1.xlsx')
df1 = pd.read_excel(excelDF, 'SheetNameThatYouWantTORead')
print(df1.columns)

暂无
暂无

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

相关问题 如何检查我的 sqlite 列是否不在我的数据框中? - How do i check if my sqlite column is not in my dataframe? 我的大部分列标题都是我的 dataframe 中的日期,无法使用 loc function - 我该如何解决这个问题? - Majority of my column headers are dates in my dataframe, not able to use the loc function - how do I fix this? 如何根据第一列但不包括第一行对 CSV 文件进行排序? - How do I sort my CSV file based on the first column but excluding the first row? 如何将我的 function 应用到 dataframe 的第一行? - How to apply my function to the first row of a dataframe? 如何在我的数据框中添加一列,说明每一行来自哪个工作表名称? Python - How do I add a column to my dataframe that says what sheet name each row is from? Python 如何在网页上使用列名和数据框中的唯一值生成动态选择字段? - How can I generate dynamic select fields on my webpage with column names and unique values from my dataframe? 如何组合我的数据框的列来创建一个我可以用作索引的日期时间列? - How do I combine columns of my dataframe to create one datetime column which I can use as my index? 如何拆分字符串并删除 dataframe 中每一行的第一项? 关键错误 18 - How can I split my string and delete the first item for every row in my dataframe? key error 18 为什么我的 pandas dataframe 索引的第一行是索引列的名称? - Why is the first row of my pandas dataframe index the name of the index column? 如何使用部分文件名作为函数的输入? - How do I use part of my file names as input for a function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM