python/panda如何将列表转换为单个单元格并以excel或cvs格式存储
[我期望得到如左侧所示的输出,我得到如右侧所示的输出] 我有一份清单:python/panda如何将列表转换为单个单元格并以excel或cvs格式存储,python,pandas,Python,Pandas,[我期望得到如左侧所示的输出,我得到如右侧所示的输出] 我有一份清单: listA = ['Vlan VN-Segment', '==== ==========', '800 30800', '801 30801', '3951 33951'] 我的输出应该是 vlan vn-segment ==== ========== 800 30800 801
listA = ['Vlan VN-Segment', '==== ==========', '800 30800', '801 30801', '3951 33951']
我的输出应该是
vlan vn-segment
==== ==========
800 30800
801 30801
3951 33951
但所有4行都显示在Excel的单个单元格中。如上
我尝试了以下方法,但输出将在Excel/cvs中的4个不同行中
my_input_file = open('n9k-1.txt')
my_string = my_input_file.read().strip()
my_list = json.loads(my_string)
#print(type(my_list))
x = (my_list[2])
print(x)
t = StringIO('\n'.join(map(str, x)))
df = pd.read_csv(t)
df2 = df.to_csv('/Users/masam/Python-Scripts/new.csv', index=False)
这个问题是有道理的,但您迄今为止尝试了什么?感谢您的帮助,输出采用excel或CSV格式的6行,我只需要一个单元格中的输出,因为每个单元格都有一个来自开关的输出我只需要一个说明,大部分代码工作正常,我收到以下行的错误“工作簿=工作簿”('data.xlsx'),无法找到“工作簿”。因为没有“工作簿”其余的代码都失败了。我做了一些研究并修改了代码,但没有得到预期的结果。请帮助看起来90%的代码都在工作,请修改该行以指向您的工作目录或您希望python将工作簿写入的任何其他目录。例如“C:/Users/your_user/Documents/my_python_source/data.xlsx”我同意,但“工作簿=工作簿('/home/users/data.xlsx')不是文件的路径,下面是“工作簿”,命令不起作用,我缺少一些导入模块?工作簿=工作簿('data.xlsx')工作表=工作簿。添加工作表()工作表。设置列('A:A',20)工作表。设置列('B:B',20)工作簿=工作簿('data.xlsx'))…这本工作簿是什么?它是一个函数还是一个类或一个正在导入的模块?如果是,工作簿中有什么?非常感谢,它给了我很多帮助
listA = ['Vlan VN-Segment', '==== ==========', '800 30800', '801 30801', '3951 33951']
listA1 = []
listA2 = []
for i in listA:
itm = i.split(' ')
listA1.append(itm[0])
listA2.append(itm[len(itm)-1])
listA1[1]='----' #replacing '====' because excel will not accept it
listA2[1]='----------' #replacing '==========' because excel will not accept it
df = pand.DataFrame.from_dict({listA1[0]:listA1,listA2[0]:listA2})
df.to_excel('C:/Users/COUNT DEXTER/Documents/my_python_source/data.xlsx', header=True, index=False)````
I hope this solves the problem.
from xlsxwriter.workbook import Workbook
for i in listA:
itm = i.split(' ')
listA1 += f'\n{itm[0]}'
listA2 += f'\n{itm[len(itm)-1]}'
workbook = Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('A:A', 20)
worksheet.set_column('B:B', 20)
# Add a cell format with text wrap on.
cell_format = workbook.add_format({'text_wrap': True})
# Write a wrapped string to a cell.
worksheet.write('A1', listA1, cell_format)
worksheet.write('B1', listA2, cell_format)
workbook.close()```
https://stackoverflow.com/questions/43537598/write-strings-text-and-pandas-dataframe-to-excel