简体   繁体   中英

I have a long list of dataframe and want to convert each to numpy array X1,X2,X3 given pandas dataframes df1,df2,df3 in python using for loop

I have a long list of pandas dataframes. The need for me is to get numpy array X1 for dataframe df1, numpy array X2 for dataframe df2, numpy array X3 for dataframe df3 without doing it one after the other. ie

X1=df1.values
X2=df2.values
X3=df3.values

Using for loops comes to mind. Anyone can help with this? example dataframe:

import pandas as pd

df1=pd.DataFrame({'number':[1,2,3],'color':['Red','Green','Blue'],'symbol':['R','G','B']}

                ,columns=['number','color','symbol'])

df2=pd.DataFrame({'number':[4,5,6],'color':['Black','Yellow','Orange'],'symbol':['B','Y','O']}

                ,columns=['number','color','symbol'])

df3=pd.DataFrame({'number':[7,8,9],'color':['Purple','White','Violet'],'symbol':['P','W','V']}

                ,columns=['number','color','symbol'])

示例数据框 df1

示例输出 numpy 数组 X1

Check if this works for you:

import pandas as pd
import numpy as np

df1=pd.DataFrame({'number':[1,2,3],'color':['Red','Green','Blue'],'symbol':['R','G','B']}

                ,columns=['number','color','symbol'])

df2=pd.DataFrame({'number':[4,5,6],'color':['Black','Yellow','Orange'],'symbol':['B','Y','O']}

                ,columns=['number','color','symbol'])

df3=pd.DataFrame({'number':[7,8,9],'color':['Purple','White','Violet'],'symbol':['P','W','V']}

                ,columns=['number','color','symbol'])

for i in range(1,4):
    globals()["X" + str(i)] = np.array(globals()["df" + str(i)])

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