2

I have a program that sorts through a large series of data and pulls a bunch of necessary values and saves them as numbers or strings.

How do I then place those values into a new dataframe?

For instance:

labels = ['A', 'B', 'C', 'D']
df = pd.DataFrame(columns=labels)

Now I want to add variables x, y, Z and the text "banana" to the DataFrame into A, B, C and D respectively.

Is there a line of code using an append-like method or something similar that will do this quickly and efficiently?

(My actual dataframe will have a multitude of columns, so a quick script is much more useful than creating an empty dataframe and changing each cell value.)

2 Answers 2

3

This should do it for you, if I understand correctly:

df.loc[len(df)] = ['x', 'y', 'Z', 'banana']

>>> df
   A  B  C       D
0  x  y  Z  banana

Or, more conveniently, as a function:

def insert_row(df, my_row):
    df.loc[len(df)] = my_row

insert_row(df, ['x', 'y', 'Z', 'banana'])
Sign up to request clarification or add additional context in comments.

2 Comments

I believe this is exactly what I am looking for as it will add the next row to the database. If it's empty - it will add row zero, and if it has 6 current entries, it will add the 7th to row 6. Thanks. Also - if I have variables, X and Y as strings, I just place df.loc[len(df)0 = [X,Y, 'Z', 'banana']?
That shouldn't be a problem: X = 'string1', Y = 'string2', df.loc[len(df)] = [X, Y, 'Z', 'banana'] works fine
0
In [1]: import pandas as pd

In [2]: df = pd.DataFrame(columns=["A", "B", "C", "D"])

In [3]: df.loc[0] = ["x", "y", "Z", "banana"]

In [4]: df
Out[4]: 
   A  B  C       D
0  x  y  Z  banana

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.