Skip to main content
 首页 » 编程设计

python之如何在 Pandas 中创建 DataFrame

2025年05月04日25lidabo

我正在使用包含 8 列的 playerStat.csv,而我只需要其中的 2 列。所以我正在尝试创建一个仅包含这两列的新 DataFrame。

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
dataset = pd.read_csv("HLTVData/playerStats.csv") 
dataset.head(20) 

我只需要 ADR 和评级。

所以我首先用数据集创建一个矩阵。

mat = dataset.as_matrix() 
#4 is the ADR and 6 is the Rating 
newDAtaSet = pd.DataFrame(dataset, index=indexMatrix,columns=(mat[:,4],mat[:,6]) ) 

但是没有成功,抛出了异常

NameError                                 Traceback (most recent call last) 
<ipython-input-10-1f975cc2514a> in <module>() 
      1 #4 is the ADR and 6 is the Rating 
----> 2 newDataSet  = pd.DataFrame(dataset, index=indexMatrix,columns=(mat[:,4],mat[:,6]) ) 
       
 
NameError: name 'indexMatrix' is not defined 

我也尝试过使用数据集。

newDataSet = pd.DataFrame(dataset, index=np.array(range(dataset.shape[0])), columns=dataset['ADR']) 
 
/home/tensor/miniconda3/envs/tensorflow35openvc/lib/python3.5/site-packages/pandas/core/internals.py in _make_na_block(self, placement, fill_value) 
   3984  
   3985         dtype, fill_value = infer_dtype_from_scalar(fill_value) 
-> 3986         block_values = np.empty(block_shape, dtype=dtype) 
   3987         block_values.fill(fill_value) 
   3988         return make_block(block_values, placement=placement) 
 
MemoryError:  

请您参考如下方法:

我认为您需要在 read_csv 中使用参数 usecols :

dataset = pd.read_csv("HLTVData/playerStats.csv", usecols=['ADR','Rating']) 

或者:

dataset = pd.read_csv("HLTVData/playerStats.csv", usecols=[4,6])