我是新手,想知道是否有人能够帮助我解决问题。
- 我已经编写了下面显示的代码。
- json文件的内容粘贴在脚本下面。
- 在json内容下面,我们可以看到脚本输出结果。
我只想将输出数据框中每个列的名称设置为国家对象的名称(例如Germany或France)。
而不是得到这个输出结果
value name value name
tag
capital Paris France Berlin Germany
population 34111000000 France 11233000000 Germany
language French France German Germany
...i would like something like this
France Germany
tag
capital Paris Berlin Germany
population 34111000000 11233000000 Germany
language French German Germany
任何帮助都将不胜感激:-)
以下是我的代码...
import numpy as np
import pandas as pd
import json
class Country(object):
def __init__(self,name):
self.name = name
self.json = name + "_Data.json"
def ImportJson(x):
ImportedJson = []
for country in x:
with open(country.json) as country_json_file:
country_data = json.load(country_json_file)
country_data_table = pd.DataFrame(country_data['data'], columns=['tag', 'value']).set_index('tag')
country_data_table['name'] = country.name
ImportedJson.append(country_data_table)
return ImportedJson
France = Country("France")
Germany = Country("Germany")
All_Countries = [France,Germany]
OpenedJson = ImportJson(All_Countries)
Country_Data = pd.concat(OpenedJson,axis=1)
print Country_Data
这里是JSON文件:
Germany_Data.json
{
"data": [
{
"tag": "capital",
"value": "Berlin"
},
{
"tag": "population",
"value": 11233000000
},
{
"tag": "language",
"value": "German"
}
],
"result_count": 33,
"page_size": 5000,
"current_page": 1,
"total_pages": 1,
"api_call_credits": 1
}
France_Data.json
{
"data": [
{
"tag": "capital",
"value": "Paris"
},
{
"tag": "population",
"value": 34111000000
},
{
"tag": "language",
"value": "French"
}
],
"result_count": 33,
"page_size": 5000,
"current_page": 1,
"total_pages": 1,
"api_call_credits": 1
}
value name value name
tag
capital Paris France Berlin Germany
population 34111000000 France 11233000000 Germany
language French France German Germany
country_data_table.rename(columns={'value':country.name}, inplace=True)
,而不是第二行代码。 - Nickil Maveli