पांडा डेटाफ़्रेम को json में कैसे परिवर्तित करें
अक्सर आपको पांडा डेटाफ़्रेम को JSON प्रारूप में परिवर्तित करने में रुचि हो सकती है।
सौभाग्य से, to_json() फ़ंक्शन का उपयोग करके ऐसा करना आसान है , जो आपको निम्न स्वरूपों में से किसी एक के साथ डेटाफ़्रेम को JSON स्ट्रिंग में परिवर्तित करने की अनुमति देता है:
- ‘स्प्लिट’: {‘इंडेक्स’ -> [इंडेक्स], ‘कॉलम’ -> [कॉलम], ‘डेटा’ -> [वैल्यू]} जैसे निर्देश
- ‘रिकॉर्ड’: [{कॉलम -> मान}, …, {कॉलम -> मान}] जैसी सूची
- ‘सूचकांक’: निर्देश जैसे {सूचकांक -> {स्तंभ -> मान}}
- ‘कॉलम’: {कॉलम -> {सूचकांक -> मान}} जैसा निर्देश
- ‘मान’: केवल मानों की सारणी
- ‘टेबल’: निर्देश जैसे {‘स्कीमा’: {स्कीमा}, ‘डेटा’: {डेटा}}
यह ट्यूटोरियल दिखाता है कि निम्नलिखित पांडा डेटाफ़्रेम का उपयोग करके डेटाफ़्रेम को छह प्रारूपों में से प्रत्येक में कैसे परिवर्तित किया जाए:
import pandas as pd #createDataFrame df = pd.DataFrame({'points': [25, 12, 15, 19], 'assists': [5, 7, 7, 12]}) #view DataFrame df assist points 0 25 5 1 12 7 2 15 7 3 19 12
विधि 1: “विभाजित करें”
df. to_json (orient=' split ') { "columns": [ "points", "assists" ], "index": [ 0, 1, 2, 3 ], "data": [ [ 25, 5 ], [ 12, 7 ], [ 15, 7 ], [ 19, 12 ] ] }
विधि 2: “रिकॉर्डिंग”
df. to_json (orient=' records ') [ { "points": 25, “assists”: 5 }, { "points": 12, “assists”: 7 }, { "points": 15, “assists”: 7 }, { "points": 19, “assists”: 12 } ]
विधि 3: “सूचकांक”
df. to_json (orient=' index ') { "0": { "points": 25, “assists”: 5 }, "1": { "points": 12, “assists”: 7 }, "2": { "points": 15, “assists”: 7 }, "3": { "points": 19, “assists”: 12 } }
विधि 4: “कॉलम”
df. to_json (orient=' columns ') { "dots": { "0": 25, "1": 12, "2": 15, "3": 19 }, "assists": { "0": 5, "1": 7, "2": 7, "3": 12 } }
विधि 5: “मूल्य”
df. to_json (orient=' values ') [ [ 25, 5 ], [ 12, 7 ], [ 15, 7 ], [ 19, 12 ] ]
विधि 6: “तालिका”
df. to_json (orient=' table ') { "plan": { "fields": [ { "name": "index", "type": "integer" }, { "name": "points", "type": "integer" }, { "name": "assists", "type": "integer" } ], "primaryKey": [ "index" ], "pandas_version": "0.20.0" }, "data": [ { "index": 0, "points": 25, “assists”: 5 }, { "index": 1, "points": 12, “assists”: 7 }, { "index": 2, "points": 15, “assists”: 7 }, { "index": 3, "points": 19, “assists”: 12 } ] }
JSON फ़ाइल कैसे निर्यात करें
आप अपने कंप्यूटर पर JSON फ़ाइल को किसी विशिष्ट फ़ाइल पथ पर निर्यात करने के लिए निम्नलिखित सिंटैक्स का उपयोग कर सकते हैं:
#create JSON file json_file = df. to_json (orient=' records ') #export JSON file with open('my_data.json', 'w') as f: f.write(json_file)
आप पांडा to_json() फ़ंक्शन का पूरा दस्तावेज़ यहां पा सकते हैं ।