3

I have several Pandas Series objects that look like this:

r = pd.Series({'a': [1,2,3,4]})
s = pd.Series({'b': [2,4,1]})
u = pd.Series({'c': [8,6]})
v = pd.Series({'d': [4,3,1]})

I'd like to convert these Series objects into a data fram with the dictionay keys as column names and the values as columns. My desired output is:

     'r'    's'    'u'    'v'
0     1      2      8      4
1     2      4      6      3
2     3      1     Nan     1
3     4     Nan    Nan    Nan

How can I create a data frame object as depicted above? I'm aware of the .fillna method, but I could not get this to work with my data. The missing values should be Nan. Thanks for the help.

4

1 回答 1

2

我认为最简单的方法是joinon index。我已经将原始变量调整为 DataFrames 以启用此功能(注意:它们应该是 DataFrames 而不是 Series)

r = pd.DataFrame({'r': [1,2,3,4]})
s = pd.DataFrame({'s': [2,4,1]})
u = pd.DataFrame({'v': [8,6]})
v = pd.DataFrame({'u': [4,3,1]})

r.join([s, u, v], how='outer')
#    r   s   v   u
# 0  1   2   8   4
# 1  2   4   6   3
# 2  3   1 NaN   1
# 3  4 NaN NaN NaN
于 2012-11-03T22:44:49.790 回答