Pandas非常规但实用的骚操作2

目录

一、骚操作

1、使用shift进行位移操作

2、使用resample对数据重采样

3、使用expanding进行累计计算操作

4、使用nlargest和nsmallest进行最大最小值操作

5、使用map和applymap进行映射操作

6、使用stack和unstack进行堆叠和解堆叠操作

7、使用rolling进行滑动窗口操作

8、使用replace进行替换操作

9、使用melt进行重塑操作

10、使用agg进行聚合操作

二、划重点


一、骚操作

1、使用shift进行位移操作

        DataFrame中的shift方法可以将数据向上或向下位移指定的行数。

import pandas as pd  
import numpy as np  
  
# 创建一个包含NaN值的DataFrame  
df = pd.DataFrame({'A': [1, 2, np.nan, 4]})  
print(df)  
  
# 使用shift方法向上位移一行,将NaN值填充到第一行  
result = df['A'].shift(-1)  
print(result)  # 输出Series([2.0, nan, 4.0, nan])
2、使用resample对数据重采样

        DataFrame中的resample方法可以按照指定的时间间隔对数据进行重采样,常用于时间序列数据的处理。

import pandas as pd  
import numpy as np  
  
# 创建一个时间序列DataFrame  
df = pd.DataFrame({'A': [1, 2, 3, 4, 5]}, index=pd.date_range('2023-01-01', periods=5))  
print(df)  
  
# 使用resample方法按天进行重采样,采用平均值作为采样值  
result = df.resample('D').mean()  
print(result)  # 输出DataFrame({'A': [1.5, 2.5, 3.5, 4.5]})
3、使用expanding进行累计计算操作

        DataFrame中的expanding方法可以对数据进行累计计算,常用于时间序列数据的处理。

import pandas as pd  
import numpy as np  
  
# 创建一个时间序列DataFrame  
df = pd.DataFrame({'A': [1, 2, 3, 4, 5]}, index=pd.date_range('2023-01-01', periods=5))  
print(df)  
  
# 使用resample方法按天进行重采样,采用平均值作为采样值  
result = df.resample('D').mean()  
print(result)  # 输出DataFrame({'A': [1.5, 2.5, 3.5, 4.5]})
4、使用nlargestnsmallest进行最大最小值操作

        DataFrame中的nlargestnsmallest方法可以找出最大的N个值和最小的N个值。

import pandas as pd  
import numpy as np  
  
# 创建一个DataFrame  
df = pd.DataFrame({'A': [3, 1, 2], 'B': [6, 4, 5]})  
print(df)  
  
# 使用nlargest方法找出B列最大的2个值  
result = df['B'].nlargest(2)  
print(result)  # 输出Series([6, 5])  
  
# 使用nsmallest方法找出A列最小的2个值  
result = df['A'].nsmallest(2)  
print(result)  # 输出Series([1, 2])
5、使用mapapplymap进行映射操作

        DataFrame中的map方法可以对一列进行映射,而applymap方法可以对整个DataFrame进行映射。

import pandas as pd  
import numpy as np  
  
# 创建一个DataFrame  
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})  
print(df)  
  
# 使用map方法将A列的值映射为新的值  
mapping_dict = {1: 'one', 2: 'two', 3: 'three'}  
result = df['A'].map(mapping_dict)  
print(result)  # 输出Series(['one', 'two', 'three'])  
  
# 使用applymap方法将整个DataFrame的值映射为新的值  
mapping_func = lambda x: x * 2  
result = df.applymap(mapping_func)  
print(result)  # 输出DataFrame({'A': [2, 4, 6], 'B': [8, 10, 12]})
6、使用stackunstack进行堆叠和解堆叠操作

        DataFrame中的stack方法可以将数据的列转换为行,而unstack方法可以将数据的行转换为列。

import pandas as pd  
import numpy as np  
  
# 创建一个多重索引的DataFrame  
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c'], columns=['x', 'y'])  
print(df)  
  
# 使用stack方法将数据的列转换为行  
result = df.stack()  
print(result)  # 输出Series([1, 4, 2, 5, 3, 6], index=MultiIndex([('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y'), ('c', 'x'), ('c', 'y')], names=['index', 'columns']))  
  
# 使用unstack方法将数据的行转换为列  
result = df.unstack()  
print(result)  # 输出DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
7、使用rolling进行滑动窗口操作

        DataFrame中的rolling方法可以进行滑动窗口操作,常用于数据处理和分析。

import pandas as pd  
import numpy as np  
  
# 创建一个DataFrame  
df = pd.DataFrame({'A': [1, 2, 3, 4, 5]})  
print(df)  
  
# 使用rolling方法进行滑动窗口操作,窗口大小为3,并计算每个窗口内的平均值  
result = df.rolling(window=3).mean()  
print(result)  # 输出DataFrame({'A': [nan, nan, 2.0, 3.0, 4.0]})
8、使用replace进行替换操作

        DataFrame中的replace方法可以对指定的值进行替换操作。

import pandas as pd  
import numpy as np  
  
# 创建一个DataFrame  
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['foo', 'bar', 'foo', 'bar', 'foo']})  
print(df)  
  
# 使用replace方法将B列中的'foo'替换为'baz'  
result = df.replace({'B': {'foo': 'baz'}})  
print(result)  # 输出DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['baz', 'bar', 'baz', 'bar', 'baz']})
9、使用melt进行重塑操作

        DataFrame中的melt方法可以对数据进行重塑操作,将宽格式的数据转换为长格式,常用于数据处理和分析。

import pandas as pd  
import numpy as np  
  
# 创建一个宽格式的DataFrame  
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})  
print(df)  
  
# 使用melt方法将数据进行重塑操作,将宽格式的数据转换为长格式  
result = df.melt()  
print(result)  # 输出DataFrame({'A': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'variable': ['B', 'B', 'B', 'C', 'C', 'C', 'B', 'B', 'B'], 'value': [4, 5, 6, 7, 8, 9, 4, 5, 6]})
10、使用agg进行聚合操作

        DataFrame中的agg方法可以对指定的列进行聚合操作,将多个值合并为一个值,常用于数据处理和分析。

import pandas as pd  
import numpy as np  
  
# 创建一个DataFrame  
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]})  
print(df)  
  
# 使用agg方法将A列和B列分别进行求和和平均值操作  
result = df.agg({'A': 'sum', 'B': 'mean'})  
print(result)  # 输出DataFrame({'A': [15], 'B': [30]})

二、划重点

        关注威信公众号 Python风控模型与数据分析,还有更多理论、代码分享等你来拿

猜你喜欢

转载自blog.csdn.net/a7303349/article/details/133419029