gpt4 book ai didi

python - Excel 行到句子 Python

转载 作者:行者123 更新时间:2023-12-01 09:06:24 25 4
gpt4 key购买 nike

假设我有一个 5 行 2 列的 Excel 文件。

apples      color
honeycrsp red
gala red
goldendel orange
fuji red
grannys green

我想将每一行放入一个重复的句子中。例如,我希望将column1和column2添加到句子中。

例如“这个苹果是 honeycrsp,颜色为红色”

这是我到目前为止编写的代码:

import pandas as pd;

FILE_PATH = "C:\\Users\\apples.xls";
xl = pd.ExcelFile(FILE_PATH);
df = xl.parse('testone');

apples = []
color =[]
apples = list(df['apples'])
color = list(df['color'])

def f(string, n, c=0):
if c < n:
print(string)
f(string, n, c=c + 1)

f('this apple is{0} with color {0}'.format(apples,color), 3)

期望的输出:

“这个苹果是 honeycrsp,颜色为红色”

“这个苹果是红苹果”

“这个苹果是橙色的金苹果”

“这个苹果是红色的富士”

“这个苹果是绿色的奶奶”

最佳答案

import pandas as pd

FILE_PATH = "C:\\Users\\apples.xls"
xl = pd.ExcelFile(FILE_PATH)
df = xl.parse('testone')

apples = list(df['apples'])
colors = list(df['color'])

for apple, color in zip(apples, colors):
print('this apple is {0} with color {1}'.format(apple, color))

输出:

this apple is honeycrsp with color red
this apple is gala with color red
this apple is goldendel with color orange
this apple is fuji with color red
this apple is grannys with color green

如果您愿意,可以将最后两行放入函数中。我认为这是一个更简单且可读的解决方案。

此外,将来要避免的一些错误:

  • 切勿使用;在Python中
  • 使用 .format 时将数字放入 {} 标记内将导致参数按索引格式化(这就是您在想要颜色的地方得到苹果的原因)

关于python - Excel 行到句子 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52011150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com