pandas:下一行不是在数据帧中打印

时间:2017-03-27 09:14:02

标签: python pandas

我正在尝试编写(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”而不是下一行。

如何打印下一行?

1 个答案:

答案 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
列表理解

strip

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