其他分享
首页 > 其他分享> > Pandas 与 CSV

Pandas 与 CSV

作者:互联网

import pandas as pd

DataFrame 与 CSV 相互转换

#读取 CSV 文件

df = pd.read_csv('./nba.csv')
print(df)               # 此时仅显示前五行和后五行
print(df.to_string())   # 此方法会显示表中所有行
# 将 DataFrame 保存为 CSV 文件

gradeList = {
    'Students'  : ['Alice', 'Bob', 'Curt', 'David', 'Eve'],
    'Chinese'   : [90, 89, 68, 88, 69],
    'Math'      : [89, 70, 89, 99, 100],
    'English'   : [89, 67, 78, 89, 67]
}
df = pd.DataFrame(data=gradeList)

df.to_csv('./gradeList.csv')        # 将 DataFrame 保存为 CSV 文件

数据处理

df = pd.read_csv('nba.csv')

head(n) 读取 DataFrame 的前 n 行

# head(n) 读取 DataFrame 的前 n 行
print(df.head(3))
            Name            Team  Number Position   Age Height  Weight  \
0  Avery Bradley  Boston Celtics     0.0       PG  25.0    6-2   180.0   
1    Jae Crowder  Boston Celtics    99.0       SF  25.0    6-6   235.0   
2   John Holland  Boston Celtics    30.0       SG  27.0    6-5   205.0   

             College     Salary  
0              Texas  7730337.0  
1          Marquette  6796117.0  
2  Boston University        NaN  

tail(n) 读取 DataFrame 的尾 n 行

# tail(n) 读取 DataFrame 的尾 n 行
print(df.tail(3))
             Name       Team  Number Position   Age Height  Weight College  \
455  Tibor Pleiss  Utah Jazz    21.0        C  26.0    7-3   256.0     NaN   
456   Jeff Withey  Utah Jazz    24.0        C  26.0    7-0   231.0  Kansas   
457           NaN        NaN     NaN      NaN   NaN    NaN     NaN     NaN   

        Salary  
455  2900000.0  
456   947276.0  
457        NaN  

info() 返回表格的一些基本信息

# info() 返回表格的一些基本信息
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 458 entries, 0 to 457
Data columns (total 9 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   Name      457 non-null    object 
 1   Team      457 non-null    object 
 2   Number    457 non-null    float64
 3   Position  457 non-null    object 
 4   Age       457 non-null    float64
 5   Height    457 non-null    object 
 6   Weight    457 non-null    float64
 7   College   373 non-null    object 
 8   Salary    446 non-null    float64
dtypes: float64(4), object(5)
memory usage: 32.3+ KB
None

标签:non,CSV,df,NaN,DataFrame,457,null,Pandas
来源: https://www.cnblogs.com/HOMEofLowell/p/16302202.html