仅列出嵌套数据框中的第一行

时间:2019-02-14 05:35:57

标签: python pandas dataframe nested

我只想在嵌套数据框中列出第一行。

示例:

{
"client" : "Mario",
"purchase" : [ 
        {
            "_id" :1,
            "date" : 01-01-2019,
            "product" : "X"
        }, 
        {
            "_id" :2,
            "date" : 05-01-2019,
            "product" : "Y"
        },
        {
            "_id" :3,
            "date" : 08-01-2019,
            "product" : "Z"
        }
    ]
},

{
"client" : "Luigi",
"purchase" : [ 
        {
            "_id" :1,
            "date" : 02-01-2019,
            "product" : "A"
        }, 
        {
            "_id" :2,
            "date" : 04-01-2019,
            "product" : "B"
        },
        {
            "_id" :3,
            "date" : 06-01-2019,
            "product" : "C"
        }
    ]
}

我需要这样的第一次购买:

Mario 01-01-2019
Luigi 02-01-2019

感谢帮助

1 个答案:

答案 0 :(得分:1)

import pandas as pd
df = pd.DataFrame(d)
df['purchase'] = df['purchase'].apply(lambda row : row[0]['date'])
df = df.rename(columns={'purchase': 'purchase_date'})

print(df)

注意:我通过在粘贴内容之外添加d来获得变量[],并在日期周围添加""

结果:

  client purchase_date
0  Mario    01-01-2019
1  Luigi    02-01-2019