简体   繁体   English

如何使用 Pandas 使用列表写入 Excel 列?

[英]How to write to an Excel column using a list of lists using Pandas?

I have this Excel (this is a preview but it's structured like that for the entire Excel)我有这个 Excel(这是一个预览,但它的结构与整个 Excel 的结构类似)

在此处输入图像描述

I have a list of lists where the food name is associated to the ID, here's a preview:我有一个列表列表,其中食物名称与 ID 相关联,这是一个预览:

id_food_list = [['6737', 'Apple'], ['6733', 'Cheese'], ['6731', 'Tomatos']]

It would like this:它会这样:

在此处输入图像描述

Since there's a column I'm ignoring (and one at the bottom too), I'm looking to do something like:由于我忽略了一列(底部也有一列),因此我希望执行以下操作:

if sub-list[1] == column value --> write sub-list[0] to corresponding 'ID' column

I created the 'Book1.xlsx' as shown in your first figure.我创建了“Book1.xlsx”,如您的第一个图所示。

import pandas as pd

id_food_list = [['6737', 'Apple'], ['6733', 'Cheese'], ['6731', 'Tomatos']]

df = pd.read_excel('Book1.xlsx', index_col=0)
for sublist in id_food_list:
    df.loc[sublist[1], 'ID'] = sublist[0]

df.to_excel('Book1.xlsx', index=False)

Since I assigned the first column as index column of the dataframe by index_col=0 , the loc can set the value by indexing the row and column names.由于我通过index_col=0将第一列分配为数据框的索引列,因此loc可以通过索引行名和列名来设置值。

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

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