Pandas CSV 只输出某一行的数据(to_csv)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40413741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas CSV output only the data in a certain row (to_csv)
提问by Elliot
I need to output only a particular row from a pandas dataframe to a CSV file. In other words, the output needs to have only the data in row X, in a single line separated by commas, and nothing else. The problem I am running into with to_CSV is that I cannot find a way to do just the data; I am always receiving an extra line with a column count.
我只需要将 Pandas 数据帧中的特定行输出到 CSV 文件。换句话说,输出中只需要包含第 X 行中的数据,一行中以逗号分隔,没有其他任何内容。我在 to_CSV 中遇到的问题是我找不到只处理数据的方法;我总是收到带有列数的额外行。
data.to_csv(filename, index=False)
gives
给
0,1,2,3,4,5
X,Y,Z,A,B,C
The first line is just a column count and is part of the dataframe, not the data. I need just the data. Is there any way to do this simply, or do I need to break out of pandas and manipulate the data further in python?
第一行只是列数,是数据框的一部分,而不是数据。我只需要数据。有什么办法可以简单地做到这一点,还是我需要摆脱Pandas并在python中进一步操作数据?
Note: the preceding example has only 1 row of data, but it would be nice to have the syntax for choosing row too.
注意:前面的例子只有 1 行数据,但如果也有选择行的语法会很好。
采纳答案by GeorgeCaoJ
You can use this
你可以用这个
data.to_csv(filename, index=False, header=False)
data.to_csv(filename, index=False, header=False)
the header
means:
的header
手段:
header : boolean or list of string, default True Write out column names. If a list of string is given it is assumed to be aliases for the column names
header : 布尔值或字符串列表,默认为 True 写出列名。如果给出字符串列表,则假定它是列名的别名
you can find more specific info in pandas.DataFrame.to_csv
您可以在pandas.DataFrame.to_csv 中找到更多具体信息
回答by Joe T. Boka
You can try this:
你可以试试这个:
df = pd.DataFrame({'A': ['a','b','c','d','e','f'], 'B': [1,2,3,4,5,6]})
A B
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f 6
You can select the row you want, in this case, I select the row at index 1
:
你可以选择你想要的行,在这种情况下,我选择行index 1
:
df.iloc[1:2].to_csv('test.csv', index=False, header=False)
The output to the csv
file looks like this (makes sure you use header=False
):
csv
文件的输出如下所示(确保您使用header=False
):
b 2
回答by sriram kumar
it seems like you are looking for filtering data from the existing dataframe and write it into .csv file.
似乎您正在从现有数据框中寻找过滤数据并将其写入 .csv 文件。
for that you need to filter your data . then apply to_csv
command.
为此,您需要过滤数据。然后应用to_csv
命令。
here is the command
这是命令
df[df.index.isin([3,4])]
df[df.index.isin([3,4])]
if this is your data
如果这是你的数据
>>> df
A B
0 X 1
1 Y 2
2 Z 3
3 A 4
4 B 5
5 C 6
then this would be your expected filtered content. then you can apply to_csv
on top of it.
那么这将是您预期的过滤内容。然后你可以to_csv
在它上面申请。
>>> df[df.index.isin([3,4])]
A B
3 A 4
4 B 5