I have a dataframe named df
with index being the date
and im trying to convert it into a Series.
date price sales
2012-01-22 4200 0
I tried
pd.Series(df['price', 'sales'], index=df.index)
but it returns an error. May I know how can I overcome it?
CodePudding user response:
try df[['price', 'sales']].iloc[0]
.
code:
import pandas as pd
df = pd.DataFrame([{'date': pd.Timestamp('2012-01-22'), 'price':4200, 'sales': 0}])
df.set_index('date', inplace=True)
print(df)
series = df[['price', 'sales']].iloc[0]
print(series)
output:
price sales
date
2012-01-22 4200 0
price 4200
sales 0
Name: 2012-01-22 00:00:00, dtype: int64
CodePudding user response:
If you have a single row and want to convert to series you can use squeeze
:
s = df.squeeze() # or df.squeeze(0)
Output:
price 4200
sales 0
Name: 2012-01-22 00:00:00, dtype: int64
Else, many options:
df.iloc[0]
df.loc['2012-01-22']
df.loc['2012-01-22', [['price', 'sales']]]
df.loc[df.index[0], [['price', 'sales']]]