看一个数据处理部分代码,遇见不知道的记录一下
import pandas as pd
读取csv:
pd.read_csv(filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], sep=lib.no_default, delimiter=None, # Column and Index Locations and Names header="infer", names=lib.no_default, index_col=None, usecols=None, squeeze=None, prefix=lib.no_default, mangle_dupe_cols=True, # General Parsing Configuration dtype: DtypeArg | None = None, engine: CSVEngine | None = None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, # NA and Missing Data Handling na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, # Datetime Handling parse_dates=None, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, # Iteration iterator=False, chunksize=None, # Quoting, Compression, and File Format compression: CompressionOptions = "infer", thousands=None, decimal: str = ".", lineterminator=None, quotechar='"', quoting=csv.QUOTE_MINIMAL, doublequote=True, escapechar=None, comment=None, encoding=None, encoding_errors: str | None = "strict", dialect=None, # Error Handling error_bad_lines=None, warn_bad_lines=None, # TODO(2.0): set on_bad_lines to "error". # See _refine_defaults_read comment for why we do this. on_bad_lines=None, # Internal delim_whitespace=False, low_memory=_c_parser_defaults["low_memory"], memory_map=False, float_precision=None, storage_options: StorageOptions = None,)
参数解释:
filepath_or_buffer:数据输入的路径:可以是文件路径、可以是URL,也可以是实现read方法的任意对象。
sep,delimiter:都是指分隔符,两个一起指定暂时不知道有啥效果
header:指定数据的表头,默认header='infer'。
infer指当没有设置names时,header=0,设定names时,header=None。
header=1,指定第二行作为表头,第二行下面的为数据,第一行被舍弃
names:也是设置表头,names=["编号", "姓名", "地址", "日期"]。
当设置names而没有设置header,表头为names设定的,第一行也被认为是数据(即使有可能是表头);当二者同时设定时,以names设定的为准,header此时起的作用是不再把header指定行及上面的行作为数据。
设定表头后,可以通过DataFrame.表头名取当列数据,如DataFrame."编号"就是指第一列
names=["编号","姓名","地址","日期"] 编号 姓名 地址 日期 id name address date 2 xxx xxxx xxxx-xx-xx
header=0 id name address date 1 xxx xxxx xxxx-xx-xx 2 xxx xxxx xxxx-xx-xx
header=0, names=["编号","姓名","地址","日期"] 编号 姓名 地址 日期 1 xxx xxxx xxxx-xx-xx 2 xxx xxxx xxxx-xx-xx
读取结果一般为DataFrame,可以用参数读取成其他格式
这篇对pandas读取csv讲解地非常详细史上最全!用Pandas读取CSV,看这篇就够了_0x8g1T9E的博客-CSDN博客_pandas读取csv文件
DataFrame.loc[]和DataFrame.iloc[]:
这两个方法都是取读到的数据中的指定行列,loc根据行或列的名称取,iloc根据行或列的索引取
# 取第一行和第二列的交叉数据 data.iloc[0,1] # 取前3行和前2列的交叉数据 data.iloc[0:3,0:2] # 下面取单行或单列的方法跟上面不太一样 data.iloc[[0],[1]] # 列表形式取出来的数据会包含其行或列的名称
DataFrame.apply():
DataFrame中的apply方法就是将函数应用到由列或行形成的一维数组上。
data.apply(function,axis=1)
function是一个输入一个变量的函数,axis指定数据轴,控制是行或列
tqdm与pandas搭配使用:
tqdm.pandas(desc='加载过程的描述') data.progress_apply(function,axois=0) # 即使用progress_apply代替原来的apply操作
DataFrame.sample():随机采样
DataFrame.sample( n: int | None = None, frac: float | None = None, replace: bool_t = False, weights=None, random_state: RandomState | None = None, axis: Axis | None = None, ignore_index: bool_t = False )
n:取样行数,如果n大于数据总量,replace必须为True
frac:按数据总量的比例取数
replace:有放回或无放回的抽样,如果为True:抽到的数据可能会相同
random_state:类似与随机数种子
axis:选取数据行(0)还是列(1)
pandas遍历数据:
1.DataFrame.iterrows() 按行遍历,返回行索引和行内容,(index, Series)
for index, row in df.iterrows(): print(index,row)
0 a xxxx
b xxxx
c xxxx
d xxxx
Name: 0, dtype: object
1 a xxxx
b xxxx
c xxxx
d xxxx
Name: 1, dtype: object
......
2.DataFrame.itertuples() 按行遍历,返回行索引和行内容
for row in df.itertuples(): print(row)
Pandas(Index=0, a=xxx, b=xxx, c=xxx, d=xxx)
Pandas(Index=1, a=xxx, b=xxx, c=xxx, d=xxx)......
3.DataFrame.iteritems() 按列遍历,返回(列名, Series)
for col in df.iteritems(): print(col)
('a', 0 xxxx
1 xxxx
......
Name: a, Length: 6503, dtype: object)('b', 0 xxxx
1 xxxx
......
Name: b, Length: 6503, dtype: object)......