简体   繁体   中英

Convert pandas column with single list of values into rows

I have the following dataframe:

  symbol           PSAR
0   AAPL  [nan,100,200]
1   PYPL  [nan,300,400]
2    SPY  [nan,500,600]

I am trying to turn the PSAR list values into rows like the following:

symbol   PSAR

AAPL     nan
AAPL     100
AAPL     200
PYPL     nan
PYPL     300
...      ...
SPY      600

I have been trying to solve it by following the answers in this post(one key difference being that that post has a list of list) but cant get there. How to convert column with list of values into rows in Pandas DataFrame .

df['PSAR'].stack().reset_index(level=1, drop=True).to_frame('PSAR')
.join(df[['symbol']], how='left')

Not a slick one but this does the job:

list_of_lists = []
df_as_dict = dict(df.values)
for key,values in df_as_dict.items():
    list_of_lists+=[[key,value] for value in values]
pd.DataFrame(list_of_lists)

returns:

    0      1
0   AAPL    NaN
1   AAPL    100.0
2   AAPL    200.0
3   PYPL    NaN
4   PYPL    300.0
5   PYPL    400.0
6   SPY     NaN
7   SPY    500.0
8   SPY    600.0

Pandas >= 0.25:

df1 = pd.DataFrame({'symbol':['AAPL', 'PYPL', 'SPY'],
               'PSAR':[[None,100,200], [None,300,400], [None,500,600]]})
print(df1)

symbol  PSAR
0   AAPL    [None, 100, 200]
1   PYPL    [None, 300, 400]
2   SPY [None, 500, 600]

df1.explode('PSAR')

    symbol  PSAR
0   AAPL    None
0   AAPL    100
0   AAPL    200
1   PYPL    None
1   PYPL    300
1   PYPL    400
2   SPY     None
2   SPY     500
2   SPY     600

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