pandas 来自标准输入的熊猫数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18495846/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:07:08  来源:igfitidea点击:

Pandas data from stdin

pythonjsonpandasstdin

提问by Fra

Is it possible to have stdin data go into a pandas DataFrame?

是否可以将标准输入数据放入 Pandas DataFrame?

Currently I'm saving the data in an intermediate jsonfile and then doing:

目前我将数据保存在一个中间json文件中,然后执行以下操作:

pandas.read_json('my_json_file.json')

but was wondering if it's possible to pipe the stdin directly in the python script. I found this: How to read from stdin or from a file if no data is piped in Python?but not sure how to do a line-by-line insertion in a pandas DF.

但想知道是否可以直接在 python 脚本中通过管道传输标准输入。我发现了这一点:如果在 Python 中没有通过管道传输数据,如何从标准输入或文件中读取?但不确定如何在 Pandas DF 中逐行插入。

回答by Viktor Kerkez

Just use the sys.stdinas a fileobject (which it actually is) and pass it to pandasread_xymethod.

只需将sys.stdin用作file对象(它实际上是)并将其传递给pandasread_xy方法。

$ cat test.py
import sys
import pandas as pd

df = pd.read_json(sys.stdin)
print df

$ cat data.json
{"a": [1,2,3,4], "b":[3,4,5,6]}

$ python test.py < data.json
   a  b
0  1  3
1  2  4
2  3  5
3  4  6