Pandas:修订间差异

无编辑摘要
无编辑摘要
第316行: 第316行:
| Series.unstack(level=- 1, fill_value=None) <br />DataFrame.unstack(level=- 1, fill_value=None)
| Series.unstack(level=- 1, fill_value=None) <br />DataFrame.unstack(level=- 1, fill_value=None)
| <code>df.unstack()</code> 将最后一层行索引转到列索引上。 <code>df.unstack(0)</code> 将第一层行索引转到列索引上。  
| <code>df.unstack()</code> 将最后一层行索引转到列索引上。 <code>df.unstack(0)</code> 将第一层行索引转到列索引上。  
|-
| pivot
| 透视,通过指定的行或列的值来重塑。
| DataFrame.pivot(index=None, columns=None, values=None)
| <code>df.pivot(index='col_1', columns='col_2', values='col_3') </code> 将col_1作为索引,col_2作为列标签,col_3作为值。
|-
|
|
|
|
|}
|}
{{了解更多
{{了解更多
第355行: 第365行:
|[https://pandas.pydata.org/docs/reference/frame.html#reshaping-sorting-transposing pandas API:DataFrame - 重塑和排序]
|[https://pandas.pydata.org/docs/reference/frame.html#reshaping-sorting-transposing pandas API:DataFrame - 重塑和排序]
}}
}}
===合并===
===合并===
{| class="wikitable"  style="width: 100%;
{| class="wikitable"  style="width: 100%;

2021年8月7日 (六) 15:45的版本

处理

重复数据

如果要标识或删除重复的行,可以使用duplicateddrop_duplicates方法。

方法 描述 不同对象的方法 示例
duplicated 标识重复行,返回一个布尔值序列。参数:
keep:默认为keep='first'标记第一次出现的重复项为False,其他都为Ture。keep='last'标记最后出现的重复项为False,其他都为Ture。keep=False标记所有重复项为Ture。
drop_duplicates 删除重复行,返回删除后的对象。参数:
keep:默认为keep='first'保留第一次出现的重复项,其他都删除。keep='last'保留最后出现的重复项,其他都删除。keep=False重复项都删除。
Series.drop_duplicates(keep='first', inplace=False)

DataFrame.drop_duplicates(subset=None, keep='first', inplace=False, ignore_index=False)

Index.drop_duplicates(keep='first')
df.drop_duplicates()删除df中所有列的值都相同的行。
df.drop_duplicates(['日期', '品种'])删除df中日期和品种列都相同的行

了解更多 >> Pandas 指南:索引和数据选择 - 重复数据 Pandas 参考:DataFrame.drop_duplicates


缺失数据

类型转换

了解更多 >> Pandas 指南:基础 - dtypes Numpy 参考:标量 Numpy 参考:数据类型对象(dtype) Pandas 参考:DataFrame.astype


文本数据

Series和Index配备了一组字符串处理方法,这些方法使您可以轻松地对数组的每个元素进行操作。也许最重要的是,这些方法会自动排除丢失/ NA值。这些可以通过str属性访问。

方法 描述 示例
Series.str.upper( ) 字符串全部大写 s.str.upper( )s字符串全部转为大写
Series.str.lower( ) 字符串全部小写 s.str.lower( )s字符串全部转为小写
df.columns.str.lower()df的列索引全部转为小写
Series.str.strip(to_strip=None) 删除字符串开始和结束位置某些字符,默认删除空格。 s.str.strip删除s两端的空格。
Series.str.lstrip(to_strip=None) 删除字符串开始位置的某些字符,默认删除空格。 s.str.lstrip( ) 删除开始位置的所有空格。
s.str.lstrip('12345.') 删除s开始位置包含'12345.'中任意的字符,如'1.开始'返回'开始'。
Series.str.rstrip(to_strip=None) 删除字符串结束位置的某些字符,默认删除空格。 s.str.rstrip( ) 删除字符串结束位置的所有空格。 s.str.rstrip('\n\t')删除字符串后面的'\n'或'\t'
Series.str.split(pat=None, n=-1, expand=False) 字符拆分。参数:
pat:拆分依据,字符串或正则表达式,默认空格。
n:拆分次数,默认全部拆分。
expand:是否将拆分的每一组展开为一列,默认不展开。
s.str.split()s按空格全部拆分。 s.str.split('/', n=2)s按'/'拆分,且只拆前面两个'/'。 s.str.split('/', n=2, expand=True)拆分后并按组展开列。
Series.str.rsplit(pat=None, n=-1, expand=False) 从结束位置开始拆分。参数同Series.str.split。 s.str.rsplit('/', n=2)s按'/'拆分,且只拆最后两个'/'。
Series.str.replace(pat, repl, n=-1, case=None, flags=0, regex=None) 替换。参数:
Series.str.cat( ) Concatenate strings in the Series/Index with given separator.
Series.str.center( ) Pad left and right side of strings in the Series/Index.
Series.str.contains( ) Test if pattern or regex is contained within a string of a Series or Index.
Series.str.count( ) Count occurrences of pattern in each string of the Series/Index.
Series.str.decode(encoding[, errors]) Decode character string in the Series/Index using indicated encoding.
Series.str.encode( ) Encode character string in the Series/Index using indicated encoding.
Series.str.endswith( ) Test if the end of each string element matches a pattern.
Series.str.extract( ) Extract capture groups in the regex pat as columns in a DataFrame.
Series.str.extractall( ) Extract capture groups in the regex pat as columns in DataFrame.
Series.str.find( ) Return lowest indexes in each strings in the Series/Index.
Series.str.findall( ) Find all occurrences of pattern or regular expression in the Series/Index.
Series.str.get(i) Extract element from each component at specified position.
Series.str.index( ) Return lowest indexes in each string in Series/Index.
Series.str.join( ) Join lists contained as elements in the Series/Index with passed delimiter.
Series.str.len( ) Compute the length of each element in the Series/Index.
Series.str.ljust( ) Pad right side of strings in the Series/Index.
Series.str.match( ) Determine if each string starts with a match of a regular expression.
Series.str.normalize( ) Return the Unicode normal form for the strings in the Series/Index.
Series.str.pad( ) Pad strings in the Series/Index up to width.
Series.str.partition( ) Split the string at the first occurrence of sep.
Series.str.repeat( ) Duplicate each string in the Series or Index.
Series.str.rfind( ) Return highest indexes in each strings in the Series/Index.
Series.str.rindex( ) Return highest indexes in each string in Series/Index.
Series.str.rjust( ) Pad left side of strings in the Series/Index.
Series.str.rpartition( ) Split the string at the last occurrence of sep.
Series.str.slice([start, stop, step]) Slice substrings from each element in the Series or Index.
Series.str.slice_replace( ) Replace a positional slice of a string with another value.
Series.str.startswith( ) Test if the start of each string element matches a pattern.
Series.str.swapcase( ) Convert strings in the Series/Index to be swapcased.
Series.str.title( ) Convert strings in the Series/Index to titlecase.
Series.str.translate( ) Map all characters in the string through the given mapping table.
Series.str.wrap( ) Wrap strings in Series/Index at specified line width.
Series.str.zfill( ) Pad strings in the Series/Index by prepending ‘0’ characters.
Series.str.isalnum( ) Check whether all characters in each string are alphanumeric.
Series.str.isalpha( ) Check whether all characters in each string are alphabetic.
Series.str.isdigit( ) Check whether all characters in each string are digits.
Series.str.isspace( ) Check whether all characters in each string are whitespace.
Series.str.islower( ) Check whether all characters in each string are lowercase.
Series.str.isupper( ) Check whether all characters in each string are uppercase.
Series.str.istitle( ) Check whether all characters in each string are titlecase.
Series.str.isnumeric( ) Check whether all characters in each string are numeric.
Series.str.isdecimal( ) Check whether all characters in each string are decimal.
Series.str.get_dummies( ) Return DataFrame of dummy/indicator variables for Series.
Series.str.capitalize( ) 转为首字母大写,其余全部小写的字符串 s.str.capitalize()
Series.str.casefold( ) 全部小写 s.str.casefold()

数据转换

方法或属性 描述 格式 示例
replace() 替换。参数:
to_replace 需要替换,可以是1.字符串,数字,正则表达式。 2.列表,其值为1中的标量,当替换值与需要替换个数相等按顺序替换,替换值只有一个则全部替换为该值。3字典。
value 替换值
inplace 是否在原数据上保存修改,默认否
Series.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')
DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')
df.replace(0, 5) 将df中0替换为5
df.replace([1, 2, 3], 0)将df中1,2,3替换为0
df.replace([1, 2, 3], [3, 2, 1])将df中1,2,3替换为3,2,1
apply() 在行或列上应用函数,可以使用聚合函数或简单转换函数。参数:
func 处理函数,可以是Python函数(自定义函数,lambda函数),或NumPy ufunc函数(如np.mean),或函数名(如'mean')
axis 轴,默认axis=0表示在每一列上应用函数,axis=1表示在每行上应用函数。
Series.apply(func, convert_dtype=True, args=(), **kwargs)
DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)
df.apply(np.mean)返回df每列的平均值。
df.apply(np.mean, axis=1)返回df每行的平均值。
df.apply(lambda x:x+100)df每个元素值+100。
df.apply(myfunc)其中myfunc是自定义函数,按照myfunc函数处理返回结果。
df.apply(['mean', 'sum'])返回df每列的平均值和每列总和。
applymap() 在每个元素上应用函数。使用聚合函数没有意义。 Series无
DataFrame.applymap(func, na_action=None, **kwargs)
df.applymap(lambda x:x+100)df每个元素值+100。
agg()
aggregate()
聚合,在行或列上使用一项或多项操作进行汇总。 Series.aggregate(func=None, axis=0, *args, **kwargs)
DataFrame.aggregate(func=None, axis=0, *args, **kwargs)
df.agg(np.mean)返回df每列的平均值
df.agg([np.mean, np.sum])返回df每列的平均值和每列总和。
df.agg({'A' : [np.mean, np.sum], 'B' : ['mean', 'max']}) A列计算平均值和总和,B列计算平均值和最大值。
transform() 在行或列上使用一项或多项操作。转化前和转化后形状要一样,不能使用聚合函数。 Series.transform(func, axis=0, *args, **kwargs)
DataFrame.transform(func, axis=0, *args, **kwargs)
pipe() 将自身(Series,DataFrame)传给函数并返回结果,用于在链中调用函数。如df.pipe(myfunc, a=100)就相当于myfunc(df, a=100) Series.pipe(func, *args, **kwargs)
DataFrame.pipe(func, *args, **kwargs)
df.agg(['mean', 'sum']).pip(my_table_style, theme='light')数据汇总后再传入自定义的my_table_style()函数进行处理。

了解更多 >> pandas 用户指南:基础功能 - 函数应用 pandas API:DataFrame - 函数应用、GroupBy和窗口函数


重塑

方法或属性 描述 格式 示例
T 转置,即行列互换。Series转置后不变。 Series.T
DataFrame.T
df.Tdf的行变列,列变行。
stack 堆叠,将列索引转为行索引。对于多层列索引的DataFrame数据改变形状有用, 当为一层列索引的DataFrame堆叠后变为Series。
参数:level 索引级别,可为正数或列表。默认level=- 1表示最后一层列索引,即最里层索引。level=0表示第一层索引。
Series无
DataFrame.stack(level=- 1, dropna=True)
df.stack() 将最后一层列索引堆叠到行索引上 df.stack(0) 将第一层列索引堆叠到行索引上 df.stack([0, 1]) 将第一层和第二层列索引堆叠到行索引上
unstack 不堆叠,将行索引转为列索引。 Series.unstack(level=- 1, fill_value=None)
DataFrame.unstack(level=- 1, fill_value=None)
df.unstack() 将最后一层行索引转到列索引上。 df.unstack(0) 将第一层行索引转到列索引上。
pivot 透视,通过指定的行或列的值来重塑。 DataFrame.pivot(index=None, columns=None, values=None) df.pivot(index='col_1', columns='col_2', values='col_3') 将col_1作为索引,col_2作为列标签,col_3作为值。

了解更多 >> pandas 用户指南:重塑与数据透视 pandas API:Series - 重塑和排序 pandas API:DataFrame - 重塑和排序


排序

方法或属性 描述 格式 示例
sort_values() 值按行或列排序。
参数:
axis:按行还是列排序,默认axis=0表示按列排序,axis=1表示按行排序
by
ascending 是否升序,默认ascending=True表示升序,ascending=False表示降序。
Series.sort_values(axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)

DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)
s.sort_values()按s的值升序排列
df.sort_values(by='col_1') df按col_1列的值升序排序
df.sort_values(by=['col_1', 'col_2'], ascending=False) df按col_1列的值降序排列,相同时再按col_2值降序。
sort_index() 行标签或列标签排序。 Series.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)

DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)
s.sort_index()按s的索引升序排列
df.sort_values(by='col_1') df按col_1列的值升序排序
nlargest() 返回前n个最大的元素。等效df.sort_values(columns, ascending=False).head(n),但性能好点。 Series.nlargest(n=5, keep='first')

DataFrame.nlargest(n, columns, keep='first')
df.nlargest(5, 'col_1') 返回col_1列降序后前5行。
nsmallest() 返回前n个最小的元素。 Series.nlargest(n=5, keep='first')

DataFrame.nsmallest(n, columns, keep='first')
df.nsmallest(10,columns='col_2') 返回col_2列升序后前5行。

了解更多 >> pandas API:Series - 重塑和排序 pandas API:DataFrame - 重塑和排序


合并

方法 描述 对象的方法 示例
concat() 沿指定轴合并Series或DataFrame。
参数:
objs,由Series或DataFrame组成的列表或字典。
axis,指定轴{0,1,…},默认为axis=0表示沿行标签合并,axis=1表示沿列标签合并。
join, {'inner','outer'},默认'outer'表示沿轴取并集,'inner'沿轴取交集。
ignore_index,布尔值,默认为False表示使用轴原来的标签(索引),True表示原来轴标签都不用,使用0开始递增的整数。
keys,列表,默认无。使用列表在轴标签(索引)外层再构造一层标签(索引)。
pandas.concat(
   objs,
   axis=0,
   join='outer',
   ignore_index=False,
   keys=None,
   levels=None,
   names=None,
   verify_integrity=False,
   sort=False,
   copy=True
)
pd.concat([df1,df2])沿行标签合并
pd.concat([df1, df4], axis=1)沿列标签合并
pd.concat([df1,df2,df3], keys=["x", "y", "z"])按行标签合并,并再添加一层行标签(由x,y,z组成)。对结果调用loc["y"]可选取df2数据
pd.concat([df1, df4], axis=1, join="inner")沿列标签取交集合并
pd.concat([s1, s2, s3], axis=1, keys=["time", "code", "price"])
append() 加入,Series的append方法用于连接多个Series。DataFrame的append方法用于从其他DataFrame对象加入多行,并返回一个新的DataFrame对象。 Series.append(to_append, ignore_index=False, verify_integrity=False)

DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=False)
s1.append(s2)s1后加入s2
df1.append(df2)df1后加入df2,返回加入后的DataFrame对象。
df1.append(df2, ignore_index=True) 忽略原来行标签,结果为从0开始递增的整数。
merge() 将DataFrame或命名的Series合并,与数据库join操作类似。
参数:
left,DataFrame或命名的Series对象。
right,另一个DataFrame或命名的Series对象。
on,要连接的列或索引级别名称,必须同时在左右对象中找到。
pandas.merge(
   left,
   right,
   how='inner',
   on=None,
   left_on=None,
   right_on=None,
   left_index=False,
   right_index=False,
   sort=False,
   suffixes=('_x', '_y'),
   copy=True,
   indicator=False,
   validate=None
   )
join() 连接另一个DataFrame的多列。 DataFrame.join(other, on=None, how='left', lsuffix=, rsuffix=, sort=False)
merge_ordered()
merge_asof()
assign() Assign new columns to a DataFrame. DataFrame.assign(**kwargs)
update() Modify in place using non-NA values from another DataFrame. Series.update(other)
DataFrame.update(other, join='left', overwrite=True, filter_func=None, errors='ignore')
insert() 在指定位置插入列。 DataFrame.insert(loc, column, value, allow_duplicates=False)

了解更多 >> pandas 用户指南:合并、加入、连接和比较 pandas API:DataFrame 合并/比较/加入/合并 pandas API:Series 合并/比较/加入/合并


比较

属性/方法 描述 Series DataFrame 示例
compare() 比较两个Series或DataFrame差异并返回,V1.1.0新增。 Series.compare(other, align_axis=1, keep_shape=False, keep_equal=False) DataFrame.compare(other, align_axis=1, keep_shape=False, keep_equal=False) s1.compare(s2) df.compare(df2)
isin() Whether each element in the Series/DataFrame is contained in values. Series.isin(values) DataFrame.isin(values)
equals() Test whether two objects contain the same elements. Series.equals(other) DataFrame.equals(other) df.equals(df2)

了解更多 >> pandas 用户指南:合并、加入、连接和比较 pandas API:DataFrame 合并/比较/加入/合并 pandas API:Series 合并/比较/加入/合并