pandas一些常用函数的使用和理解
Posted Icy Hunter
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pandas一些常用函数的使用和理解相关的知识,希望对你有一定的参考价值。
pandas库的一些用法
- 1.创建DataFrame
- 2.dataframe.columns(更改列名)
- 3.dataframe列索引、行索引
- 4.pd.read_csv()、dataframe.to_csv()
- 5.dataframe.sort_value()
- 6.dataframe.describe()
1.创建DataFrame
import pandas as pd
import numpy as np
f = pd.DataFrame(np.arange(20).reshape(4, 5), index=["c", "a", "d", "b"])
print(f)
结果
2.dataframe.columns(更改列名)
import pandas as pd
import numpy as np
f = pd.DataFrame(np.arange(20).reshape(4, 5), index=["c", "a", "d", "b"])
f.columns = ["A", "B", "C", "D", "E"]
print(f)
结果
3.dataframe列索引、行索引
import pandas as pd
import numpy as np
f = pd.DataFrame(np.arange(20).reshape(4, 5), index=["c", "a", "d", "b"])
print("f[0]:")
print(f[0])
f.columns = ["A", "B", "C", "D", "E"]
print('f["A"]')
print(f["A"])
print('f.loc["c"]')
print(f.loc["c"])
结果
4.pd.read_csv()、dataframe.to_csv()
读存取csv文件,十分方便
import pandas as pd
import numpy as np
f = pd.DataFrame(np.arange(20).reshape(4, 5), index=["c", "a", "d", "b"])
f.columns = ["A", "B", "C", "D", "E"]
f.to_csv("a.csv", index=0, encoding="utf-8") # 行索引不保存
# f.to_csv("a.csv", encoding="utf_8_sig") # 这个保存用excel打开中文不会乱码
ff = pd.read_csv("a.csv", encoding="utf-8", sep=",") # 默认就是逗号相隔,sep="\\t"就可以读tsv了
print(ff)
csv文件
5.dataframe.sort_value()
对列值进行排序,ascending=False表示降序排
import pandas as pd
import numpy as np
f = pd.DataFrame(np.arange(20).reshape(4, 5), index=["c", "a", "d", "b"])
f.columns = ["A", "B", "C", "D", "E"]
f.iloc[0][1] = 20
f = f.sort_values(by=["A", "B"], ascending=False) # 首先按A列降序,其次按B列降序
print(f)
结果
6.dataframe.describe()
用于计算一些常用的统计数
import pandas as pd
import numpy as np
f = pd.DataFrame(np.arange(20).reshape(4, 5), index=["c", "a", "d", "b"])
f.columns = ["A", "B", "C", "D", "E"]
f = f.describe()
print(f)
结果
以上是关于pandas一些常用函数的使用和理解的主要内容,如果未能解决你的问题,请参考以下文章