首页 > 解决方案 > 尝试使用 for 循环将数据框中的值存储在字典中

问题描述

#Names of columns in the dataframe 
featureList = df.columns
print(featureList)
#number of columns in the dataframe
noOfCol = len(df.axes[1])
print(noOfCol)
#number of rows
noOfRow = len(df.axes[0])
print(noOfRow)
featureList = df.columns
print(featureList)
#number of columns in the dataframe
noOfCol = len(df.axes[1])
print(noOfCol)
#number of rows
noOfRow = len(df.axes[0])
print(noOfRow)

#creating a dictionary for storing all the cols separately
#using for loop: way4
dfDic = dict()
colCounter = 0
for featureName in featureList:
  dfDic = {featureName:df.iloc[:,[colCounter]]} 
  colCounter +=1

print(dfDic)

这是我的代码,下是结果。我想存储所有功能的列值,但只存储最后一列。

标签: pythonpandasdataframedictionary

解决方案


您可以使用简单地将 Pandas 数据框转换为字典df.to_dict(orient="list")


推荐阅读