Lynn
Lynn

Reputation: 4388

Creating new dataframe from preexisting dataframe using Python

I have a large file, df1, that I wish to extract some data from its cells and then create a new file, df2 with a new column name and datetime column:

df

        A   B   C   D   E
        
        1   2   3   4   5

Desired output:

    Date       Value

    1/1/2020   3

This is what I am doing:

   import pandas as pd
   import numpy as mp

   df1 = pd.read_csv('df1'csv')


   for index.row in df.iterrows():
       print row.loc[0:3] = df2['value']





   df2.to_csv('df2.csv')

I am stuck on how to create the new column and add the date into this new dataframe. Any suggestion is appreciated.

Upvotes: 0

Views: 45

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34046

Assuming Date is a constant value you need to add, you can do this:

In [1393]: df
Out[1393]: 
   A  B  C  D  E
0  1  2  3  4  5

In [1395]: x = df.at[0, 'C'] # Pick 1st row's column C

In [1396]: y = '1/1/2020'

In [1398]: df = pd.DataFrame({'Date':[y], 'Value':[x]})

In [1399]: df
Out[1399]: 
       Date  Value
0  1/1/2020      3

You can then write this df to an excel file like below:

df.to_excel('file.xlsx')

Upvotes: 1

Related Questions