Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create single row python pandas dataframe

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)

like image 745
HeXor Avatar asked Aug 04 '17 10:08

HeXor


People also ask

How do you get one row in pandas?

If you want the first row of dataframe as a dataframe object then you can provide the range i.e.[:1], instead of direct number i.e. It will select the rows from number 0 to 1 and return the first row of dataframe as a dataframe object. Learn More about iloc[] and loc[] properties of Dataframe, Pandas Dataframe.

How do I make one row in python?

Python DB API allows us to fetch only a single row. To fetch a single row from a result set we can use cursor. fetchone() . This method returns a single tuple.


Video Answer


1 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 
like image 182
MaxU - stop WAR against UA Avatar answered Oct 04 '22 04:10

MaxU - stop WAR against UA