Excel行到句子

2024-04-19 02:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个5行2列的Excel文件。你知道吗

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

我想把每一行放在一个重复的句子里。例如,我希望在句子中添加column1和column2。你知道吗

例如“这个苹果是红色的”

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

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)

期望输出:

“这个苹果是红色的”

“这个苹果是红色的”

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

“这个苹果是富士红的”

“这个苹果是绿色的”


Tags: 文件path苹果dfstringredexcellist
2条回答
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时,将数字放在{}标记中会导致参数按索引进行格式化(因此您得到想要颜色的苹果的原因)

将数据作为数据帧读取并使用apply

import pandas as pd

data = pd.DataFrame({'apples':["honeycrsp","gala","goldendel","fuji","grannys"],'color':["red","red","orange","red","greeen"]})

def concat(r):
    return return 'this apple is ' + r[0] + ' with color ' + r[1]

data.apply(concat,axis=1)

以上程序显示以下内容

0       this apple is honeycrsp with color red
1            this apple is gala with color red
2    this apple is goldendel with color orange
3            this apple is fuji with color red
4      this apple is grannys with color greeen

如果不想显示索引

s = data.apply(concat,axis=1)
print(s.to_string(index=False))

这就是结果

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 greeen

相关问题 更多 >