【发布时间】:2019-08-24 03:28:03
【问题描述】:
我从 API 中提取数据,它会为我需要放入 pandas DataFrame 的每个条目返回一个字典列表。让这变得困难的是,被拉出来的字典总是不同的。
3 个例子:
[{'name': 'A', 'value': '1'},
{'name': 'B', 'value': 'DateTimeValue'},
{'name': 'C', 'value': '15'}]
[{'name': 'A', 'value': '2'},
{'name': 'D', 'value': 'StringValue'},
{'name': 'C', 'value': '15'}]
[{'name': 'A', 'value': '5'},
{'name': 'B', 'value': 'DateTimeValue'},
{'name': 'C', 'value': '19'},
{'name': 'F', 'value': '25.123'}]
我需要将“名称”值作为 DF 中的列,将“值”值作为行。在最终的应用程序中,我需要在 for 循环中一次提取数百个。
我得到的最接近的是在 for 循环中创建几个单行数据帧并尝试合并它们。但是,合并只是使用 _y 和 _x 创建了新列。我需要数据框仅在出现新名称时创建新列,例如上面的 F。
这是我尝试过的
df = pd.DataFrame(columns=['A']) # A is the only common column
for dict in dict_list:
data = getdata(API_stuff = ApiStuff, dicts = dict) #returns one list of dicts
df1 = pd.DataFrame(dict) #get the data of one dict
df1 = df1.transpose()
df1.reset_index(inplace=True)
df1 = df1.drop(columns= ['index'])
df1.columns = df1.loc[0] # makes the column names the dict 'names'
df1.drop(df1.index[0],inplace=True) # drop the duplicate row
df1.index = ['Message-ID']
# the above code creates a one row dataframe with the 'name' values as columns
df = pd.merge(df, df1, on='A', how='outer') # merge one df on the previous ones
输出如下:
A B C A_x D C_x A_y B_x C_y F
0 1 DT 15
1 2 SV 15
2 5 DT 19 25.123
在空格中包含 NaN
我需要输出是
A B C D F
0 1 DT 15 NaN NaN
1 2 NaN 15 SV NaN
2 5 DT 19 NaN 25.123
我知道有更好的方法可以做到这一点,但我无法将各个部分组合在一起。谢谢!
【问题讨论】:
标签: python pandas dataframe dictionary