首页 > 解决方案 > 如何将数据框中的多列从输出转换为excel?

问题描述

我正在尝试将输出提取到 excel 文件中

import pandas as pd
file1='excel1.xlsx'
file2='excel2.xlsx'

df1=pd.read_excel(file1)
df2=pd.read_excel(file2)
l=df2['col1'].tolist()

for row in range(len(l)):
    for index,row1 in df1.iterrows():
        l[row].replace(row1['emp'],row1['desc'])
out=[a.replace('','_') for a in l]
length=[len(o) for o in out]

final_df=pd.DataFrame(out,index=df2['col1'],columns=['desc']
final_df.to_csv('output.csv')

在上面的代码中,它只在 excel 中给出变量结果,但我也需要在 excel 中获得长度变量结果。

当我试图在列中给出长度变量时,它给出的列应该是 1 但给出 2。

 final_df=pd.DataFrame(out,index=df2['col1'],columns=['desc','Length']
 final_df.to_csv('output.csv')

任何人都可以请帮助如何在excel中获得变量和长度变量结果吗?

标签: python-3.xexcelpandas

解决方案


... previous code section

out=[a.replace('','_') for a in l]
length=[len(o) for o in out]

final = {'desc': a, 'Length': length}
final_df=pd.DataFrame(final,
                      index=df2['col1']
final_df.to_csv('output.csv')

推荐阅读