I have a Pandas Series object with a date-index and dict-values like this:
timeSeries = pd.Series({'2014-05-01': {'property1': 1, 'property2': 2},
'2014-05-02': {'property1': 3, 'property2': 4}})
I know that every dict contains the same keys ( property1
and property2
). Is there a way to get a Series without a loop with just property1
as value.
Ie I want:
propertySeries = pd.Series({'2014-05-01': 1,
'2014-05-02': 3})
You can convert Series
to numpy array
by values
and then use DataFrame
constructor:
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
Another slowier solution:
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
If you created the time series yourself use 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
If you created the time series yourself, you could create a DataFrame instead:
timeSeries = pd.DataFrame({'2014-05-01': {'property1': 1, 'property2': 2},
'2014-05-02': {'property1': 3, 'property2': 4}}).T
timeSeries['property1']
# 2014-05-01 1
# 2014-05-02 3
# Name: property1, dtype: int64
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.