Create single row python pandas dataframe
Question:
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)
Answers:
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
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.
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
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)
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
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.
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