[英]Read excel file with pandas and store values into Python dict with the column names as keys
I have following excel:我有以下excel:
type name latitude longitude
--------------------------------------------
area area1 50.33 4.23
building building1 - -
I'm using pandas to read in the excel file using following function:我正在使用 pandas 使用以下函数读取 excel 文件:
def read_excel(self,sheet_name):
df = pd.read_excel(io=self.excel_file, sheet_name=sheet_name)
dict = df.to_dict()
I get following output:我得到以下输出:
{
'type': { 0: 'area', 1: 'building' },
'name': { 0: 'area1', 1: 'building1' },
'latitude': { 0: 50.33, 1: nan },
'longitude': { 0: 4.23, 1: nan }
}
I would like to have the following output:我想要以下输出:
[
{
'type': 'area',
'name': 'area1',
'latitude': 50.33,
'longitude': 4.23
},
{
'type': 'building',
'name': 'building1',
'latitude': nan,
'longitude': nan
}
]
To achieve this, I have written the following function:为此,我编写了以下函数:
def read_excel(self,sheet_name):
df = pd.read_excel(io=self.excel_file, sheet_name=sheet_name)
dict = df.to_dict()
objects = []
for i in range(0,len(df.index)):
temp = {}
temp['type'] = dict['type'][i]
temp['name'] = dict['name'][i]
temp['latitude'] = dict['latitude'][i]
temp['longitude'] = dict['longitude'][i]
objects.append(temp)
print(objects)
This produces the output I want.这会产生我想要的输出。 However, I would like to have a solution that is more dynamic, eg that I don't need create a temp dict with assigning statically column names.但是,我想要一个更动态的解决方案,例如,我不需要创建一个带有静态分配列名的临时字典。
Any suggestions to achieve this?有什么建议可以实现这一目标吗?
pass orient='records'
to to_json
:)将orient='records'
传递给to_json
:)
always refer to the documentation as a debugging step!始终将文档作为调试步骤! https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html
您是否尝试将其定位为records
:
print(df.to_dict(orient='records'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.