I want to create a DataFrame with one instance per columns of my data and the type of that instance but I can't find a way to create a list of the types (in order to put it in the DataFrame).
Here is an example of what I want:
my_original_data = pd.DataFrame({'col1': [1,2,3],'col2':['Hello','foo','bar'],'col3':[dt.datetime(2000,1,1),dt.datetime(1999,12,2),dt.datetime(1950,5,3)]})
And I want a new DataFrame with first row = columns names, second row = first values, ie [1, 'Hello', dt.datetime(2000,1,1)] and third row = types of these values, ie [int, str, date].
How to create this last line?
Before to transform three lists into DataFrame, I tried
first_values = [my_original_data.loc[0,column] for column in df.columns]
types = [type(my_original_data.loc[0,column]) for column in df.columns]
It returns "TypeError: 'list' object is not callable". Same if I try
types = map(type,first_values)
list(types)
Try this:
cols = my_original_data.columns.tolist()
data = my_original_data.loc[0].tolist()
dtypes = list(map(type, data))
new_df = pd.DataFrame([[cols], [data], [dtypes]], columns=['df_desc'])
Similar to what u tried:
first = my_original_data.iloc[0,:].values
types = [type(my_original_data.iloc[0,column]) for column in range(len(my_original_data.columns))]
final_df = pd.DataFrame([first,types],index=['first','type'],columns = my_original_data.columns)
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.