Reputation: 1339
Just a basic question but which block me a lot. How can we extract a column from a DataFrame and have a DataFrame as output ?
Suppose that we have :
>>> dfM
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 17544 entries, 2015-01-01 00:00:00 to 2016-12-31 23:00:00
Data columns (total 23 columns):
T1 17544 non-null values
T2 17544 non-null values
>>> df = dfM['T1']
Here df is not a DataFrame. I found a subterfuge by copy the DataFrame and del all columns but it's very time consumming.
Alexis
Upvotes: 0
Views: 3948
Reputation: 78590
You can use [[]]
instead of []
:
df = dfM[['T1']]
For example:
from pandas import DataFrame
df = DataFrame(dict(a=range(10), b=range(10)))
type(df['b'])
# <class 'pandas.core.series.Series'>
type(df[['b']])
# <class 'pandas.core.frame.DataFrame'>
This works because it is passing a list of 1 (['b']
) to the column subset operator.
Upvotes: 1
Reputation: 4604
One solution is to create a DataFrame with the column you want and the original index:
df = pandas.DataFrame(dfM.T1, index = dfM.index)
Upvotes: 0