Home > database >  Is there a non-deprecated clean way to append a series or an array to just one of a dataframe's
Is there a non-deprecated clean way to append a series or an array to just one of a dataframe's

Time:02-04

I have a dataframe with two columns and a series, I want to attach this series to the end of a column and have the values of the other one set to NaN. These appended values should not be merged with what is already in the df. I know there is append, but that is deprecated so I wondered what the alternatives were for this task nowadays.

This is what I did and how I want it to look in the end (without the conversion to float for some reason):

a = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})
b = pd.Series([7, 8, 9], name='two')
pd.concat([a, pd.DataFrame({'one': np.nan, 'two': b})], ignore_index=True)
    one two
0   1.0 4
1   2.0 5
2   3.0 6
3   NaN 7
4   NaN 8
5   NaN 9

This would be more problematic with more columns and I just wanted a cleaner way for the sake of it.

CodePudding user response:

concat works fine without needing to manually pad, just convert your Series to_frame:

a = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})
b = pd.Series([7, 8, 9], name='two')

out = pd.concat([a.convert_dtypes(), b.to_frame()], ignore_index=True)

NB. the convert_dtypes enables to use a NA that avoids conversion to float. Also, the name of the Series is important to assign the column, if the Series doesn't already have a name use to_frame(name='two').

Output:

    one  two
0     1    4
1     2    5
2     3    6
3  <NA>    7
4  <NA>    8
5  <NA>    9

CodePudding user response:

a = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})
b = pd.Series([7, 8, 9], name='two')
a = a.to_dict('list')
a['two'].extend(b)
pd.DataFrame.from_dict(a, orient='index').T

If you have more columns, use a for loop for the keys.

  • Related