编写一个返回字典的函数,其中键是数据框的列名称,值是“数字”、“分类”、“序数”、“日期/时间”或“文本”之一,对应每列的特征类型。
我能够将数据作为数据框导入。然后我将 df 转换成字典。然后我得到了键作为列,但我在为每列分配值(“数字”、“分类”、“序数”、“日期/时间”或“文本”)时遇到了麻烦。
# Importing the pandas package
import pandas as pd
def helper(df):
# Creating data frame from csv.gz File. Enter the appropriate file path
cobra = pd.read_csv(df, compression='gzip')
cobra_dict = cobra.to_dict()
dict_keys = cobra.keys()
print(dict_keys)
helper(df)
Expected Results:
In [1]: helper(df[['offense_id','beat','x','y']])
Out[1]: {'beat': 'categorical',
'offense_id': 'ordinal',
'x': 'numeric',
'y': 'numeric'}
最佳答案
IIUC,
如果您想要与上面的输出完全相同,您可能需要创建一个映射字典,但这应该可行,我们可以zip
列和您的dtypes
到两个列表中,创建一个 dict
,其中列作为键,值作为数据类型。
def helper(df):
# Creating data frame from csv.gz File. Enter the appropriate file path
cobra = pd.read_csv(df, compression='gzip')
cobra_dict = dict(zip(cobra.columns.tolist(),cobra .dtypes.tolist()))
print(cobra_dict)
在我自己的样本 df 上。
print(my_dict)
{'A': dtype('O'), 'B': dtype('int64'), 'C': dtype('float64')}
关于python - 字典键是数据帧中的列,值是列的特征类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468533/