Home > other >  Add Series as a new row into DataFrame triggers FutureWarning
Add Series as a new row into DataFrame triggers FutureWarning

Time:09-21

Trying to add a new row of type Series into a DataFrame, both share the same columns/index:

df.loc[df.shape[0]] = r

Getting:

FutureWarning: In a future version, object-dtype columns with all-bool values will not be included in reductions with bool_only=True. Explicitly cast to bool dtype instead.

Which comes from inference module.

CodePudding user response:

try:

df
    c1  c2  c3      c4
0   1   3   True    abc
1   2   4   False   def

d = {'c1': 3, 'c2': 5, 'c3': True, 'c4': 'ghi'} 
s = pd.Series(d) 

s
c1       3
c2       5
c3    True
c4     ghi
dtype: object

df.loc[df.shape[0]] = s.to_numpy() 

df
    c1  c2  c3      c4
0   1   3   True    abc
1   2   4   False   def
2   3   5   True    ghi

CodePudding user response:

base:

import pandas as pd

data = pd.DataFrame.from_dict({
    'Name': ['Nik', 'Kate', 'Evan', 'Kyra'],
    'Age': [31, 30, 40, 33],
    'Location': ['Toronto', 'London', 'Kingston', 'Hamilton']
})

df = pd.DataFrame(data)
df
Name Age Location
0 Nik 31 Toronto
1 Kate 30 London
2 Evan 40 Kingston
3 Kyra 33 Hamilton

solution:

import pandas as pd

data = pd.DataFrame.from_dict({
    'Name': ['Nik', 'Kate', 'Evan', 'Kyra'],
    'Age': [31, 30, 40, 33],
    'Location': ['Toronto', 'London', 'Kingston', 'Hamilton']
})

df = pd.DataFrame(data)

# Using pandas.concat() to add a row
r = pd.DataFrame({'Name':'Creuza', 'Age':69, 'Location':'São Gonçalo'}, index=[0])
df2 = pd.concat([r,df.loc[:]]).reset_index(drop=True)
df2
Name Age Location
0 Creuza 69 São Gonçalo
1 Nik 31 Toronto
2 Kate 30 London
3 Evan 40 Kingston
4 Kyra 33 Hamilton
  • Related