简体   繁体   中英

iterate through csv columns to create multiple python dataframe

I am trying to create multiple data frames using the columns of a excel csv file. This is where I have been able to get to

 import pandas as pd file = pd.read_csv('file.csv') df = pd.DataFrame(file) cols = df.columns #column names are 'Date', 'Stock 1', 'Stock 2', etc - I have 1000 columns for i in range(len(cols)): df[i] = df[['Date',b(i)]] 

So the end result is I want multiple dataframes. The first dataframe is with columns 1 and 2 (so Date and Stock 1), the second dataframe is with columns 1 and 3 (so Date and Stock 2), the third dataframe is with columns 1 and 3, creating new dataframe all the way to Columns 1 and 1000.

I have tried several ways and either get index in not callable or I tried with usecols and I get usecols must be strings or integers.

Can anyone help me with this. Conceptually it is easy but I can not get the code right. Thank you.

This does what you are asking:

all_dfs = []
for col in df.columns:
    if col != 'Date':
        df_current = df[['Date', col]]
        all_dfs.append(df_current)

Or as one line:

all_dfs = [df[['Date', col]] for col in df.columns if col != 'Date']

But you probably don't want to do that. There's not much point. What are you really trying to do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM