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

标签 python performance pandas dictionary series

我有一个 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/

相关文章:

python - 使用动态名称在 Pandas 中创建新数据框还会添加新列

python openpyxl读取excel太慢

python - 在 python 中绘制 sympy 结果

mysql - Perl:将 $dbh 交给模块。安全性和性能?

python - 下面的代码有更快的实现吗?

javascript - 在 JS 中使用 RequireJS/AMD 可以获得多少速度?

python - 字符串索引的 Pandas WHERE 子句?

python - 组合包含相似子字符串的列表元素

python - "len() of unsized object"错误

python - 将 Pandas 数据框转换为嵌套 JSON