'Convert dataframe with 2 columns into series
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?
Solution 1:[1]
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
Solution 2:[2]
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']]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mikm |
| Solution 2 | mozway |
