Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

pandas - Adding new columns to a data frame while creating new indices

Trying to dynamically create a data frame by creating a series and adding it to the frame as shown below:

df = pd.DataFrame()

s = pd.Series({ 1: 'one', 2: 'two', 3: 'three'})

df['aaa'] = s
s = pd.Series({ 1: 'one', 5: 'two', 6: 'three'})

df['bbb'] = s

    aaa    bbbb
    ----   ----
1   one    one
2   two    nan
3   three  nan

However, this results in a frame which doesn't have the new rows corresponding to indices '5' and '6'. Is there any way can add new columns and indices if they are missing from the frame?

question from:https://stackoverflow.com/questions/65889119/adding-new-columns-to-a-data-frame-while-creating-new-indices

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with concat

df = pd.DataFrame()
s = pd.Series({ 1: 'one', 2: 'two', 3: 'three'})
df['aaa'] = s
s = pd.Series({ 1: 'one', 5: 'two', 6: 'three'}, name='bbb')
df = pd.concat([df,s], axis=1)
df
Out[150]: 
     aaa    bbb
1    one    one
2    two    NaN
3  three    NaN
5    NaN    two
6    NaN  three

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...