1

Questions:

  1. How to make empty Pandas DataFrame, name 2 columns in it?

  2. How to add a row for previously created DataFrame?

Can somebody help please? My code below doesn't work properly, it returns strange DataFrame.

My code:

data_set = pd.DataFrame(columns=['POST_TEXT', 'TARGET'])

data_set[data_set.shape[0]] = ['Today is a great day!', '1']

Code result:

enter image description here

1
  • 1
    you need to use loc to assign a row data_set.loc[data_set.shape[0]] = ['Today is a great day!', '1'], otherwise it is a column Commented Oct 26, 2021 at 19:22

2 Answers 2

1
data_set = pd.DataFrame(columns=['POST_TEXT', 'TARGET'])

# output
Empty DataFrame
Columns: [POST_TEXT, TARGET]
Index: []

# add row
data_set = data_set.append({"POST_TEXT": 5, "TARGET": 10}, ignore_index=True)

# output
  POST_TEXT TARGET
0         5     10

So to append row you have to define dict where key is name of the column and value is the value you want to append.

If you would like to add row and populate only one column:

data_set = data_set.append({"POST_TEXT": 50}, ignore_index=True)

# output
   POST_TEXT  TARGET
0       50.0     NaN
Sign up to request clarification or add additional context in comments.

Comments

1

instead of adding the value post-creation, it is possible to add it during creation:

data_set = pd.DataFrame(columns=['POST_TEXT', 'TARGET'], data=[['Today is a great day!', '1']])

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.