53

I want to create a python pandas DataFrame with a single row, to use further pandas functionality like dumping to *.csv.

I have seen code like the following being used, but I only end up with the column structure, but empty data

import pandas as pd

df = pd.DataFrame()
df['A'] = 1
df['B'] = 1.23
df['C'] = "Hello"
df.columns = [['A','B','C']]

print df

Empty DataFrame
Columns: [A, B, C]
Index: []

While I know there are other ways to do it (like from a dictionary), I want to understand why this piece of code is not working for me!? Is this a version issue? (using pandas==0.19.2)

HeXor
  • 1,075
  • 2
  • 11
  • 20
  • 4
    You need two wrap the first one in brackets: `df['A'] = [1]` – ayhan Aug 04 '17 at 10:22
  • 2
    Or, mention the first row, `df.loc[0, 'A'] = 1`? – Zero Aug 04 '17 at 10:25
  • 4
    alternatively, if you add `df = pd.DataFrame(index=[0])` - then your code should work properly – MaxU - stand with Ukraine Aug 04 '17 at 10:28
  • @MaxU this indeed makes the above code runnable as it is. But the code as posted above is not runnable itself (or at least creates empty dataframs), is this correct? So the above code can be considered as buggy!? – HeXor Aug 07 '17 at 09:33
  • @HeXor, it depends on the definition of "buggy code"... Pandas allows us to do things in many different ways. IMO the most idiomatic way of creating DFs is to collect the data and then create DF at once compared to adding single rows, which is usually pretty inefficient... – MaxU - stand with Ukraine Aug 07 '17 at 09:44

3 Answers3

81
In [399]: df = pd.DataFrame(columns=list('ABC'))

In [400]: df.loc[0] = [1,1.23,'Hello']

In [401]: df
Out[401]:
   A     B      C
0  1  1.23  Hello

or:

In [395]: df = pd.DataFrame([[1,1.23,'Hello']], columns=list('ABC'))

In [396]: df
Out[396]:
   A     B      C
0  1  1.23  Hello
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
6

If you are creating the DataFrame from a dict you can do the following:

>>> data = dict(A=1, B=1.23, C='Hello')
>>> df = pd.DataFrame(data, index=[0])
>>> df
   A     B      C
0  1  1.23  Hello
James Hirschorn
  • 7,032
  • 5
  • 45
  • 53
0

I know this is an old post, but based on this explanation in this post Creating an empty Pandas DataFrame, then filling it?

We should not be doing dataframe adding. I am asking this because I am doing something similar but I opted for the solution in the post I shared over this one.

mas192
  • 23
  • 4
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 17 '22 at 06:52