【问题标题】:Writing to an exact cell in Excel using Python使用 Python 写入 Excel 中的精确单元格
【发布时间】:2020-08-05 14:19:07
【问题描述】:

非常感谢您的帮助!这是我现在的代码:我只需要触发一次,所以 1 次迭代,这是解决方案吗? B 列留出一个空位,然后添加“2”。可能是因为它看的是索引:

import pandas as pd
from pathlib import Path

data_folder = Path(PATH)

file_to_open = data_folder / "excelbestand.xlsx"

df = pd.read_excel(file_to_open)

data_x = 4
data_y = 2

  
df.loc[df.index.max()+1, ['A']] = data_x

df.loc[df.index.max()+1,['B']] = data_y

df.to_excel(file_to_open, index = False)

【问题讨论】:

  • 请贴出你已经写好的代码。
  • 我现在在下面的评论中做了,对不起!
  • edit您的问题并将您的代码移到那里。另外,阅读editing help 并在代码块中格式化您的代码。
  • 好吧,大卫!

标签: python excel pandas


【解决方案1】:

首先,您似乎首先需要读取 pandas 中的数据框:

import pandas as pd

df = pandas.read_excel("name_your_file.xlsx",sheet_name = 'name_your_sheet')
num_iterations = 10 # Number of times you want to perform action
while i <= num_iterations:
    data_x = df['A'].count()
    df.loc[df.index.max()+1] = [data_x]

【讨论】:

  • import pandas as pd from pathlib import Path data_folder = Path("FILE PATH") file_to_open = data_folder / "excelbestand.xlsx" df = pd.read_excel(file_to_open,sheet_name = 'sheet') num_iterations = 2 data_x = 4 i=0 而 i 没有当我触发此查询时发生。
  • 如果您想执行类似 sql 的查询,那么您的问题应该说明:查看 pandasql pypi.org/project/pandasql
  • 这不是关于 sql 部分,而是关于在 excel 中的精确单元格中添加某个值
  • 你需要先读取excel文件,我建议pandas函数pd.read_excel。然后,您可以通过 df.loc 或 df.iloc 方法访问您 ant 的每一行。请记住它是零索引
  • 查看我的新答案,它应该可以解决您有关使用 iloc 的问题。
【解决方案2】:

如您所见,pd.iloc 非常强大:df.iloc[ 行号,列号]: columns : A,B,C,D 列号 = 0,1,2,3

import pandas as pd
from pathlib import Path

data_folder = Path(PATH)

file_to_open = data_folder / "excelbestand.xlsx"

df = pd.read_excel(file_to_open)

num_iterations = 1
data_x = 4
i=0
##### In this while you are appending the count of column "A" to the end of column "A"

while i <= num_iterations:   
    df.loc[df.index.max()+1, 0] = [data_x]
    i += 1
###########code for adding to las cell of column B 
i2 = 0    
while i2 <= num_iterations:
    df.loc[df.index.max()+1,1] = [data_x]
    i += 1

df.to_excel(file_to_open, index = False)

【讨论】:

  • 非常感谢!我编辑了我的帖子,还有一个问题要解决 Andres!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 2015-09-17
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多