Python Forum
Appending a row to a DataFrame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Appending a row to a DataFrame
#4
Your code works fine for me. After appending the dictionary the dataframe looks like this:
Output:
....py:15: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. df.append ({'first':'Anthony2','last':'Birch2'}, ignore_index = True) # this line does not work. first last 0 Sam Smith 1 Jane Donahue 2 John Doe 3 Anthony1 Birch1
It works. For me. For now. I am using pandas 1.4.1. Since append is depreciated you should not use it in any code you are writing. Instead of using append() use concat().

To use concat you will need two dataframes. This requires a slight modification to the row that you want to add.
import pandas as pd
 
sampledata = {
    'first' : ['Sam', 'Jane', 'John'],
    'last': ['Smith', 'Donahue', 'Doe'],
}
 
df = pd.DataFrame(sampledata)
print(df)
 
values = ['Anthony1','Birch1']
length = len(df)
df.loc[length] = values

df2 = pd.concat((df, pd.DataFrame({'first':['Anthony2'],'last':['Birch2']}))) 
print(df2)
I would avoid doing this:
values = ['Anthony1','Birch1']
length = len(df)
df.loc[length] = values
df.loc[] is not using an index in the sense of an index in a Python list. For example, this is a perfectly fine dataframe.
import pandas as pd
df = pd.DataFrame(columns=["first", "last"])
df.loc[1] = ["Anthony", "Birch"]
df.loc['X'] = ["Sam", "Smith"]
df.loc[3.14] = ["John", "Doe"]
print(df)
Output:
first last 1 Anthony Birch X Sam Smith 3.14 John Doe
When you do "df[len(df)] = values", this might append a new row to the table and assign it an appropriate row index, but it could also replace an existing row that uses the index len(df).
import pandas as pd
 
df = pd.DataFrame({"Odd":[1, 3, 5], "Even":[2, 4, 6]})[1:]
print(df)

df.loc[len(df)] = [7, 8]
print(df)
Output:
Odd Even 1 3 4 2 5 6 Odd Even 1 3 4 2 7 8 OOPS! Index 2 was already used
Reply


Messages In This Thread
Appending a row to a DataFrame - by azizrasul - Oct-11-2022, 10:03 PM
RE: Appending a row to a DataFrame - by Am1n3 - Oct-11-2022, 11:16 PM
RE: Appending a row to a DataFrame - by azizrasul - Oct-12-2022, 12:04 AM
RE: Appending a row to a DataFrame - by deanhystad - Oct-12-2022, 06:26 AM
RE: Appending a row to a DataFrame - by azizrasul - Oct-13-2022, 12:28 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020