简体   繁体   English

如何将这个json对象转换为pandas数据框?

[英]How do I turn this json object into a pandas dataframe?

I have a csv file that I turn into a json so that I can turn it into a panda data-frame. 我有一个csv文件,可以将其转换为json,以便可以将其转换为熊猫数据框。

Here is my code, 这是我的代码,

def create_png():

    f = open('sticks.csv', 'r')
    reader = csv.DictReader( f, fieldnames = ("xstk", "stk") )
    out = json.dumps( [row for row in reader ] )
    print out

    df = DataFrame([
        #TODO
    ])

The line 'print out' prints out "[{"xstk": "1", "stk": "0"}, {"xstk": "0", "stk": "1"}, {"xstk": "1", "stk": "0"}]" 'print out'行打印出[[{“ xstk”:“ 1”,“ stk”:“ 0”},{“ xstk”:“ 0”,“ stk”:“ 1”},{“ xstk” :“ 1”,“ stk”:“ 0”}]“

So what can I put into #TODO to make the code run and turn this into a simple two column dataframe? 那么我可以在#TODO中放入什么来使代码运行并将其转换为简单的两列数据框? I have looked at Create pandas dataframe from json objects but it is a complicated example. 我看过从json对象创建熊猫数据帧,但这是一个复杂的示例。

Simply read the string of the json in directly to read_json : 只需将json的字符串直接读取到read_json

In [11]: pd.read_json('[{"xstk": "1", "stk": "0"}, {"xstk": "0", "stk": "1"}, {"xstk": "1", "stk": "0"}]')
Out[11]:
   stk  xstk
0    0     1
1    1     0
2    0     1

However, if you already have a csv you should really read it in directly using read_csv : 但是,如果您已经有一个csv,则应该使用read_csv直接阅读它:

df = pd.read_csv('sticks.csv', names=["xstk", "stk"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM