首页 > 解决方案 > 如何使用python将两个excel列转换为json?

问题描述

我有一个类似这样的excel文件:

name   gender   fac1(radio)   fac2(tv)   fac3(cycle)   fac4(bike)   hasCard   cardNo
a1     f         y              y           n             y          n         
a2     m         n              n           y             n          y         AHJS5684

如何从上面的 xls 文件中获得如下结构

"name": "a1",
"gender": "f",
"facilities": ["radio", "tv", "bike"],
"card": {
   "exists": "n"
   "cardNo": ""
}

到目前为止,我刚刚在我的代码中阅读了 excel 文件:

import pandas as pd
#reading excel
df = pd.read_excel("C:\\Users\\Desktop\\Culture\\Artist_Data\\EZCC\\Madur.xlsx")
new_df = df.assign(facilities = df.filter(like = 'fac').apply(lambda x: x.str.lower().dropna().tolist(), axis=1))
d = df.to_dict('records')

上面的代码根本没有给出想要的结果。

标签: pythonjsonexcel

解决方案


Pandas 非常适合作为数据帧处理,而不是 json 格式。但是apply可以将数据帧的行(或列)转换为包括字典在内的任何内容,list并将熊猫系列简单地转换为列表。

这意味着所需的转换可以是:

labels = {'fac1(radio)': 'radio', 'fac2(tv)': 'tv', 'fac3(cycle)': 'cycle', 
          'fac4(bike)': 'bike' }
d = list(df.fillna('').apply(lambda x: {
    "name": x['name'],
     "gender": x['gender'],
     "facilities": [labels[i] for i in labels.keys() if x[i] == 'y'],
     "card": {
         "exists": x['hasCard'],
         "cardNo": x['cardNo']
     }}, axis=1))

你可以控制它

print(json.dumps(d, indent=2))

按预期给出:

[
  {
    "name": "a1",
    "gender": "f",
    "facilities": [
      "radio",
      "tv",
      "bike"
    ],
    "card": {
      "exists": "n",
      "cardNo": ""
    }
  },
  {
    "name": "a2",
    "gender": "m",
    "facilities": [
      "cycle"
    ],
    "card": {
      "exists": "y",
      "cardNo": "AHJS5684"
    }
  }
]

推荐阅读