[英]How to create a list with the types of element of another list in Python
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).我想创建一个 DataFrame,其中每列数据有一个实例以及该实例的类型,但我找不到创建类型列表的方法(以便将其放入 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].我想要一个新的 DataFrame,第一行 = 列名,第二行 = 第一个值,即 [1, 'Hello', dt.datetime(2000,1,1)] 和第三行 = 这些值的类型,即 [int , str, 日期]。
How to create this last line?如何创建最后一行?
Before to transform three lists into DataFrame, I tried在将三个列表转换为 DataFrame 之前,我尝试过
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".它返回“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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.