gpt4 book ai didi

python - 从系列词典中提取系列

转载 作者:行者123 更新时间:2023-11-30 22:47:59 26 4
gpt4 key购买 nike

我有一个 Pandas Series 对象,其日期索引和字典值如下:

timeSeries = pd.Series({'2014-05-01': {'property1': 1, 'property2': 2},
'2014-05-02': {'property1': 3, 'property2': 4}})

我知道每个字典都包含相同的键(property1property2)。有没有办法获得一个系列没有循环仅使用property1作为值。

即我想要:

 propertySeries = pd.Series({'2014-05-01': 1,
'2014-05-02': 3})

最佳答案

您可以通过valuesSeries转换为numpy array然后使用 DataFrame构造函数:

print (timeSeries.values.tolist())
[{'property1': 1, 'property2': 2}, {'property1': 3, 'property2': 4}]

df = pd.DataFrame(timeSeries.values.tolist(), index=timeSeries.index)
print (df)
property1 property2
2014-05-01 1 2
2014-05-02 3 4

print (df['property1'])
2014-05-01 1
2014-05-02 3
Name: property1, dtype: int64

print (df['property2'])
2014-05-01 2
2014-05-02 4
Name: property2, dtype: int64

另一个较慢的解决方案:

print (timeSeries.apply(lambda x: x['property1'])) 
2014-05-01 1
2014-05-02 3
dtype: int64

print (timeSeries.apply(lambda x: x['property2']))
2014-05-01 2
2014-05-02 4
dtype: int64

如果您自己创建时间序列,请使用 DataFrame.from_dict :

timeSeries = pd.DataFrame.from_dict({'2014-05-01': {'property1': 1, 'property2': 2},
'2014-05-02': {'property1': 3, 'property2': 4}},
orient='index')


print (timeSeries)
property1 property2
2014-05-01 1 2
2014-05-02 3 4

关于python - 从系列词典中提取系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40344456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com