简体   繁体   中英

Creating a DataFrame from list of Series

I have below list of series:

import pandas as pd
my_series_a = pd.Series([1,2,2,4,5], name='Group_A')
my_series_b = pd.Series([50,50,70], name='Group_B')
my_series_c = pd.Series([333,222,111,111], name='Group_C')
my_list = [my_series_a, my_series_b, my_series_c]

I need to create a DataFrame with 2 columns [Group, Sub-Group]:

Group: Name of the Series
Sub-Group: Unique values from each Series

Result should be:

Group     Sub-Group
Group_A    1
Group_A    2
Group_A    4
Group_A    5
Group_B    50
Group_B    70
Group_C    333
Group_C    222
Group_C    111

Use a list comprehension and pd.unique() function:

In [11]: pd.DataFrame([(arr.name, i) for arr in my_list for i in pd.unique(arr)],
                      columns=['Group', 'Sub-Group'])
Out[11]: 
     Group  Sub-Group
0  Group_A          1
1  Group_A          2
2  Group_A          4
3  Group_A          5
4  Group_B         50
5  Group_B         70
6  Group_C        333
7  Group_C        222
8  Group_C        111

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