pandas4

创建 DataFrame 数据类型
与 Sereis 不同,DataFrame 可以存在多列数据。一般情况下,DataFrame 也更加常用。

1 通过 NumPy 数组创建 DataFrame

# 定义时间序列作为 index
num_arr=np.random.randn(6,4) 
# 传入 numpy 随机数组
columns=['A','B','C','D'] 
# 将列表作为列名
df1=pd.DataFrame(num_arr,index=dates,columns=columns)
df1

2 通过字典数组创建 DataFrame

data={'animal': 
['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
 'age': 
 [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3]}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df2=pd.DataFrame(data,index=labels)
df2

3 预览 DataFrame 的前 5 行数据
此方法对快速了解陌生数据集结构十分有用。

df2.head() 
# 默认为显示 5 行,可根据需要在括号中填入希望预览的行数

4 查看 DataFrame 的后 3 行数据

df2.tail(3)

5 查看 DataFrame 的索引

df2.index

6 查看 DataFrame 的列名

df2.columns

7 查看 DataFrame 的数值

df2.values

8 查看 DataFrame 的统计数据

df2.describe()

9 DataFrame 转置操作

df2.T

10 对 DataFrame 进行按列排序

df2.sort_values(by='age') # 按 age 升序排列

11 对 DataFrame 数据切片

df2[1:3]

12 对 DataFrame 通过标签查询(单列)

df2['age']

13 对 DataFrame 通过标签查询(多列)

df2[['age','animal']] 
# 传入一个列名组成的列表

14 对 DataFrame 通过位置查询

df2.iloc[1:3] # 查询 2,3 行

15 DataFrame 副本拷贝

# 生成 DataFrame 副本,方便数据集被多个不同流程使用
df3=df2.copy()
df3

16 判断 DataFrame 元素是否为空

df3.isnull() 
# 如果为空则返回为 True

17 添加列数据

num=pd.Series([0,1,2,3,4,5,6,7,8,9],index=df3.index)
df3['No.']=num 
# 添加以 'No.' 为列名的新数据列
df3

18 根据 DataFrame 的下标值进行更改。

# 修改第 2 行与第 1 列对应的值 3.0 → 2.0
df3.iat[1,0]=2 
# 索引序号从 0 开始,这里为 1, 0
df3

19 根据 DataFrame 的标签对数据进行修改

df3.loc['f','age']=1.5
df3

20 DataFrame 求平均值操作

df3.mean()

21 对 DataFrame 中任意列做求和操作

df3['visits'].sum()

22 将字符串转化为小写字母

string = pd.Series(['A', 'B', 'C', 'Aaba'])
print(string)
string.str.lower()

23 将字符串转化为大写字母

string.str.upper()

24 对缺失值进行填充

df4=df3.copy()
print(df4)
df4.fillna(value=3)

25 删除存在缺失值的行

df5=df3.copy()
print(df5)
df5.dropna(how='any')

26 DataFrame 按指定列对齐

left = pd.DataFrame({'key': ['foo1', 'foo2'], 'one': [1, 2]})
right = pd.DataFrame({'key': ['foo2', 'foo3'], 'two': [4, 5]})
​
print(left)
print(right)
​
# 按照 key 列对齐连接,只存在 foo2 相同,所以最后变成一行
pd.merge(left, right, on='key')

27 CSV 文件写入

df3.to_csv('animal.csv')
#to_excel()
print("写入成功.")

28 CSV 文件读取

df_animal=pd.read_csv('animal.csv')
#pd.read_excel('animal.xlsx', 'Sheet1', index_col=None, na_values=['NA'])
df_animal

猜你喜欢

转载自blog.csdn.net/qq_36264495/article/details/80337951