其他分享
首页 > 其他分享> > Pandas 函数

Pandas 函数

作者:互联网

1.data structure:

Series:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers,Python objects, etc.).

s = pd.Series(data, index=index, dtype, name, copy))

data:

index:

    索引,默认为0 ~ (length-1),也可自行以list形式设置

   eg1 data为randn生成

s = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"])
s
a 0.469112
b -0.282863
c -1.509059
d -1.135632
e 1.212112
dtype: float64

  eg2 data 为dict

d = {"b": 1, "a": 0, "c": 2}
pd.Series(d)
Out:
b 1
a 0
c 2

# data为dict类型时,若index不默认设置,则key变为索引值

DataFrame

DataFrame 是一个表格型的数据结构

 

pandas.DataFrame( data, index, columns, dtype, copy)

eg1: data 为 dict

# Pre-defined lists
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr =  [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]

# Import pandas as pd
import pandas as pd

# Create dictionary my_dict with three key:value pairs: my_dict
my_dict = {'country' : names, 'drives_right' : dr,'car_per_cap' : cpc}

# Build a DataFrame cars from my_dict: cars
cars=pd.DataFrame(my_dict)

# Definition of row_labels
row_labels = ['US', 'AUS', 'JPN', 'IN', 'RU', 'MOR', 'EG']

# Specify row labels of cars 设置行label,列label默认为key
cars.index=row_labels   

print(cars)

Pandas CSV 

1. 读入csv数据

# Import the cars.csv
cars = pd.read_csv('cars.csv',index_col=0)

#index_col=0 即用csv中第1列作为 row label,index_col=1, 即用csv中第2列为 row label,由此类推... ; 默认情况下: index_col 为0,1,2,3...

print(cars.to_string())

to_string() 用于返回 DataFrame 类型的数据,如果不使用该函数,则输出结果为数据的前面 5 行和末尾 5 行,中间部分以 ... 代替。

outcome

 

2. 将 DataFrame 存储为 csv 文件:

cars.to_csv('cars.csv')

3.数据处理

读取前n行

head( n ) 方法用于读取前面的 n 行,如果不填参数 n ,默认返回 5 行。

print(cars.head(n))

读取后n行

print(cars.tail(n))

获取某列

++++++++以label+++++++++为索引

#print as series
print(cars['country'])

#print as dataframe:
 print(cars[['country']])


# Print out DataFrame with country and drives_right columns
print(cars[['country','drives_right']])

+++++++以序号为索引+++++++++

# Print out first 3 observations
print(cars[0:3])

# Print out fourth, fifth and sixth observation
print(cars[3:6])

打印某行/某列(通用)

#打印某行

print as series:

cars.loc['RU'] 
cars.iloc[4]

print as dataFrame:

cars.loc[['RU']]
cars.iloc[[4]]

cars.loc[['RU', 'AUS']]
cars.iloc[[4, 1]]

打印某个位置的元素

print as series:

cars.loc['IN', 'cars_per_cap']
cars.iloc[3, 0]


cars.loc[['IN', 'RU'], ['cars_per_cap', 'country']] # [[行m,行n],[列i,列j]]
cars.iloc[[3, 4], [0, 1]]

print as dataFrame:
cars.loc[[['IN', 'RU']], [['cars_per_cap', 'country']]]

4.数据清洗

  删除空白数据

DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

(1)Pandas默认的空白数字

Pandas 把 n/a NA 当作空数据,na 不是空数据

(2)设置空白数字

import pandas as pd

missing_values = ["n/a", "na", "--"]

df = pd.read_csv('property-data.csv', na_values = missing_values)

(3)判断某列各个单元格是否为空

print (df['NUM_BEDROOMS'].isnull())

返回:

(4)删除

删除指定列中包含空值的行

df.dropna(subset=['ST_NUM'], inplace = True)

(5)replace

对整个dataFrame进行操作

df.fillna(12345, inplace = True)

 对指定列进行操作

df['PID'].fillna(12345, inplace = True)

删除重复数据

dupicated()判断,如果对应的数据是重复的,duplicated() 会返回 True,否则返回 False。

print(df.duplicated())
结果:

0    False
1    False
2     True
3    False
dtype: bool

drop_duplicates() 删除

df.drop_duplicates(inplace=True)

删除符合某些条件的数据

import pandas as pd

person = {
  "name": ['Google', 'Runoob' , 'Taobao'],
  "age": [50, 40, 12345]    # 12345 年龄数据是错误的
}

df = pd.DataFrame(person)

for x in df.index:
  if df.loc[x, "age"] > 120:
    df.drop(x, inplace = True)

print(df.to_string())

5.计算

中位数/均值/众数

median()、mean() 和 mode()

x = df["ST_NUM"].mean()

代码/例子参考 datacamp/ 菜鸟教程

标签:index,函数,df,cars,pd,print,True,Pandas
来源: https://blog.csdn.net/qq_43123477/article/details/122769637