Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用lineterminator从pandas到csv删除最后一个空行_Python_Pandas_Dataframe_Csv_Series - Fatal编程技术网

Python 使用lineterminator从pandas到csv删除最后一个空行

Python 使用lineterminator从pandas到csv删除最后一个空行,python,pandas,dataframe,csv,series,Python,Pandas,Dataframe,Csv,Series,我需要将一些列拆分为第一行,将其余的列拆分为第二行 我已将它们存储在一个数据帧中,例如: columnA columnB columnC columnD A B C D 到文本文件sample.txt: A,B C,D 代码如下: cleaned_data.iloc[:, 0:1].to_csv("report_csv.txt", encoding='utf-8', index=False, header=

我需要将一些列拆分为第一行,将其余的列拆分为第二行

我已将它们存储在一个数据帧中,例如:

columnA   columnB   columnC   columnD
   A         B         C         D
到文本文件
sample.txt

A,B
C,D
代码如下:

cleaned_data.iloc[:, 0:1].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False, line_terminator='')
cleaned_data.iloc[:,1:].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False, mode='a', line_terminator='')
它应该按照
sample.txt
中的预期生成。然而,第三行是空的,我不希望它存在。我尝试了
lineterminator=''
,它不适用于
'
,但它可以工作,例如
'
'abc'

我确信有比使用我所写的更好的方法来生成示例文本文件。我准备好了其他的选择


但是,如何删除最后一行空行?我使用的是python 3.8,我无法重现您的问题,但可能是数据帧中的字符串包含尾随换行符。我正在linux上运行Pandas 0.23.4

import pandas
print(pandas.__version__)
我使用命令创建了我认为您的数据帧包含的内容

df = pandas.DataFrame({'colA':['A'], 'colB': ['B'], 'colC':['C'], 'colD':['D']})
要检查单元格的内容,可以使用
df['colA'][0]

获取第一列和第二列所需的索引是

df.iloc[:, 0:2]
我获得CSV的方式不依赖于
lineterminator

df.iloc[:, 0:2].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False)
df.iloc[:,2:].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False, mode='a')
当我跑的时候

with open('report_csv.txt','r') as file_handle:
dat = file_handle.read()
我从
dat
获得
'A,B\nC,D\n'

要在最后一行中不获取尾随换行符,请使用
To_string()

然后,我们可以通过运行

with open('output.txt','r') as file_handle:
    dat = file_handle.read()

dat
包含
'A B\nC D'
。如果空格不是可接受的分隔符,则可以在写入文件之前用
替换它们。

我使用的是pandas 1.1.4。。。根据您的结果,它的结尾仍然有
\n
。我的预期输出是
'A,B\nC,D'
@user6308605-我已经用
to_string()
方法更新了我的答案,该方法消除了尾随的换行符。
with open('output.txt','r') as file_handle:
    dat = file_handle.read()