假设我有一个包含 5 行和 2 列的 Excel 文件。
apples color
honeycrsp red
gala red
goldendel orange
fuji red
grannys green
我想将每一行放入一个重复的句子中。例如,我希望将列 1 和列 2 添加到句子中。
例如"这个苹果是红色的
蜂蜜"这是我到目前为止编码的内容:
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)
期望输出:
"这个苹果是红色的
蜂蜜""这个苹果是红色的晚会">
"这个苹果是橙色的金色苹果">
"这个苹果是红色的富士">
"这个苹果是绿色的奶奶">
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中使用;在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