[英]Convert a list of dictionaries to dataframe
我有一个字典列表,我想将其转换为 dataframe。该列表具有以下结构:
[{'year': 2010, 'month': 1, 'weather': DataFrame},
{'year': 2010, 'month': 2, 'weather': DataFrame},
.
.
.
{'year': 2011, 'month': 12, 'weather': DataFrame}]
我希望 dataframe 具有以下列:年、月和 DataFrame 的列
由于您没有提供示例 output 或仅提供天气 Dataframe 本身,我只能建议以下解决方案。
第一个是最简单的:
import pandas as pd
your_name_list = [
{'year': 2010, 'month': 1, 'weather': DataFrame},
{'year': 2010, 'month': 2, 'weather': DataFrame}
]
result = pd.DataFrame(your_name_list)
Output:
year month weather
0 2010 1 temperature wind 0 30 0
1 2010 2 temperature wind 0 30 0
第二种解决方案是我们需要获取字典的所有列,同时获取Weather Dataframe,前提是weather有一行,否则go都会down:
import pandas as pd
your_name_list = [
{'year': 2010, 'month': 1, 'weather': pd.DataFrame([{'temperature': 30, 'wind': 0}])},
{'year': 2010, 'month': 2, 'weather': pd.DataFrame([{'temperature': 40, 'wind': 1}])}
]
df1 = pd.DataFrame(your_name_list)
df2 = pd.DataFrame(columns=['temperature', 'wind'])
del df1["weather"]
for i in your_name_list:
df2 = df2.append(i["weather"], ignore_index=True)
result = pd.concat([df1, df2], axis=1)
Output:
year month temperature wind
0 2010 1 30 0
1 2010 2 40 1
最后一个解决方案,在我看来是最合乎逻辑的,是天气 dataframe 代码只有两列(天气状况和值本身),我们需要从这些列中获取并连接结果:
import pandas as pd
your_name_list = [
{'year': 2010, 'month': 1, 'weather': pd.DataFrame([{'weather_condition': "temperature", 'value': 30},
{'weather_condition': "wind", 'value': 0}])},
{'year': 2010, 'month': 2, 'weather': pd.DataFrame([{'weather_condition': "temperature", 'value': 40},
{'weather_condition': "wind", 'value': 1}])}
]
df1 = pd.DataFrame(your_name_list)
df2 = pd.DataFrame(columns=['temperature', 'wind'])
del df1["weather"]
for i in your_name_list:
df2 = df2.append(i["weather"].assign(idx=i["weather"].groupby("weather_condition").cumcount()).pivot_table(
columns="weather_condition",
values="value",
aggfunc="first"), ignore_index=True)
result = pd.concat([df1, df2], axis=1)
Output:
year month temperature wind
0 2010 1 30 0
1 2010 2 40 1
当然,有许多细微差别我无法考虑,但我希望我至少能部分帮助解决您的问题。
如果您提出更详细的问题,我会尽量在评论中回答您的问题。
这是另一个有用的链接 - 与您的问题类似的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.