我正在尝试编写(excel文件)/打印数据框,其中列值由下一行(\ n)组成。
>>> textbox = ""
>>> textbox+=str('So, so you think you can tell \n')
>>> textbox+=str('Heaven from hell')
>>> print textbox
So, so you think you can tell
Heaven from hell
>>> df1 = pd.DataFrame({'lyric':[textbox]})
>>> df1
lyric
0 So, so you think you can tell \nHeaven from hell
>>> print df1
lyric
0 So, so you think you can tell \nHeaven from hell
所以当我打印df或写一个excel文件时,我看到的是打印出“\ n”而不是下一行。
如何打印下一行?
答案 0 :(得分:0)
我认为您需要通过使用\n
拆分来创建字符串列表,然后删除开始和结束空白:
splitlines
解决方案:
df1 = pd.DataFrame({'lyric':textbox.splitlines()})
df1.lyric = df1.lyric.str.strip()
print (df1)
lyric
0 So, so you think you can tell
1 Heaven from hell
split
解决方案:
print (textbox.split('\n'))
['So, so you think you can tell ', 'Heaven from hell']
df1 = pd.DataFrame({'lyric':textbox.split('\n')})
df1.lyric = df1.lyric.str.strip()
print (df1)
lyric
0 So, so you think you can tell
1 Heaven from hell
列表理解
df1 = pd.DataFrame({'lyric':[x.strip() for x in textbox.split('\n')]})
print (df1)
lyric
0 So, so you think you can tell
1 Heaven from hell
编辑:
我认为你需要replace
:
df1 = pd.DataFrame({'lyric':[textbox]})
df1.lyric = df1.lyric.str.replace('\n', '')
print (df1)
lyric
0 So, so you think you can tell Heaven from hell