简体   繁体   中英

Extract series objects from Pandas DataFrame

I have a dataframe with the columns

['CPL4', 'Part Number', 'Calendar Year/Month', 'Sales', 'Inventory']

For each 'Part Number', 'Calendar Year/Month' will be unique on each Part Number.

I want to convert each part number to a univariate Series with 'Calendar Year/Month' as the index and either 'Sales' or 'Inventory' as the value.

How can I accomplish this using pandas built-in functions and not iterating through the dataframe manually?

In pandas this is called a MultiIndex. Try:

import pandas as pd
df = pd.DataFrame(file, 
        index=['Part Number', 'Calendar Year/Month'], 
        columns = ['Sales', 'Inventory'])

you can use the groupby method such has:

grouped_df = df.groupby('Part Number')

and then you can access the df of a certain part number and set the index easily such has:

new_df = grouped_df.get_group('THEPARTNUMBERYOUWANT').set_index('Calendar Year/Month')

if you only want the 2 columns you can do:

print new_df[['Sales', 'Inventory']]]

From the answers and comments here, along with a little more research, I ended with the following solution.

temp_series = df[df[ "Part Number" == sku ] ].pivot(columns = ["Calendar Year/Month"], values = "Sales").iloc[0]

Where sku is a specific part number from df["Part Number"].unique()

This will give you a univariate time series(temp_series) indexed by "Calendar Year/Month" with values of "Sales" EG:

1.2015     NaN
1.2016     NaN
2.2015     NaN
2.2016     NaN
3.2015     NaN
3.2016     NaN
4.2015     NaN
4.2016     NaN
5.2015     NaN
5.2016     NaN
6.2015     NaN
6.2016     NaN
7.2015     NaN
7.2016     NaN
8.2015     NaN
8.2016     NaN
9.2015     NaN
10.2015    NaN
11.2015    NaN
12.2015    NaN
Name: 161, dtype: float64

<class 'pandas.core.series.Series'>])

from the columns

['CPL4', 'Part Number', 'Calendar Year/Month', 'Sales', 'Inventory']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM