1

I'm adding a first row from a dictionary to index 0 to Dataframe.

df = pd.DataFrame({
    "names": ["a", "a", "a"],
    "org_names": ["a", "a", "a"],
    "math" : ["!not_div", "=", "*"],
    "values": [1, 2, 3],
    "end_result" : ["", 1,2]
})

data = {"interception": 1,
        "a": 2,
        "b": 3,
        "c": 5,
        "d": 6
        }

df1 = pd.DataFrame([{
    "names": list(data.keys())[0],
    "org_names": "",
    "math" : "",
    "values": "",
    "end_result" : 1,
}])

new_df = pd.concat([df1, df], axis=0)

output:


          names org_names      math values end_result
0  interception                                     1
0             a         a  !not_div      1           
1             a         a         =      2          1
2             a         a         *      3          2

Is there a better way to do this? That's not using the concat?

shaftel
  • 17
  • 6

1 Answers1

1

According to this answer using pd.concat() is the most efficient way I'm afraid.

But you could define a function that will accomplish exactly what you want, as follows:

# Adds a row (represented as a dict or list) to the top of a DataFrame.
def append_front(df, r):  
    return pd.concat([pd.DataFrame([r], columns=df.columns), df], axis=0,  ignore_index=True)
  • This function has the row take on the same column names as the original DataFrame (columns=df.columns), allowing it can be passed as a list rather than a dict. Remove this argument if you do not want this behaviour.

  • The ignore_index argument will reassign all the index values so that they are all unique.

Your code can then be changed to the following:

# Original DataFrame
df = pd.DataFrame({
    "names": ["a", "a", "a"],
    "org_names": ["a", "a", "a"],
    "math" : ["!not_div", "=", "*"],
    "values": [1, 2, 3],
    "end_result" : ["", 1,2]
})

data = {"interception": 1,
        "a": 2,
        "b": 3,
        "c": 5,
        "d": 6
        }

# Row to add to the top of the DataFrame
row = {
    "names": list(data.keys())[0],
    "org_names": "",
    "math" : "",
    "values": "",
    "end_result" : 1,
}

"""
Works also for lists:

row = [
    list(data.keys())[0],
    "",
    "",
    "",
    1
]
"""

# New DataFrame formed by adding the row to the original DataFrame.
new_df = append_front(df, row)

The resulting DataFrame:

          names org_names      math values end_result
0  interception                                     1
1             a         a  !not_div      1           
2             a         a         =      2          1
3             a         a         *      3          2
user21283023
  • 936
  • 8