Python酷库之旅-第三方库Pandas(028)

目录

一、用法精讲

71、pandas.tseries.api.guess_datetime_format函数

71-1、语法

71-2、参数

71-3、功能

71-4、返回值

71-5、说明

71-6、用法

71-6-1、数据准备

71-6-2、代码示例

71-6-3、结果输出

72、pandas.util.hash_array函数

72-1、语法

72-2、参数

72-3、功能

72-4、返回值

72-5、说明

72-6、用法

72-6-1、数据准备

72-6-2、代码示例

72-6-3、结果输出 

73、pandas.util.hash_pandas_object函数

73-1、语法

73-2、参数

73-3、功能

73-4、返回值

73-5、说明

73-6、用法

73-6-1、数据准备

73-6-2、代码示例

73-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

71、pandas.tseries.api.guess_datetime_format函数
71-1、语法
# 71、pandas.tseries.api.guess_datetime_format函数
pandas.tseries.api.guess_datetime_format(dt_str, dayfirst=False)
Guess the datetime format of a given datetime string.

Parameters:
dt_strstr
Datetime string to guess the format of.

dayfirstbool, default False
If True parses dates with the day first, eg 20/01/2005

Warning

dayfirst=True is not strict, but will prefer to parse with day first (this is a known bug).

Returns:
str or None
ret
datetime format string (for strftime or strptime), or None if it can’t be guessed.
71-2、参数

71-2-1、dt_str(必须)一个或多个日期时间字符串,函数将尝试从这些字符串中猜测出日期时间的格式,如果传入的是列表,函数会尝试从列表中第一个非空字符串进行猜测。

71-2-2、dayfirst(可选,默认值为False)用于控制日期时间字符串中日和月的顺序,如果设置为True,则假定日期字符串中的第一个数字是日(DD/MM/YYYY),如果设置为False(默认值),则假定第一个数字是月(MM/DD/YYYY),这个参数对于解析一些可能具有不同日/月顺序的日期时间字符串非常有用。

71-3、功能

        用于猜测给定日期时间字符串(dt_str)的格式的一个实用工具。

71-4、返回值

        返回值是一个字符串,表示猜测到的日期时间格式,这个格式字符串遵循Pandas接受的日期时间格式约定,通常与Python的datetime.strptime和datetime.strftime方法兼容。

71-5、说明

        该函数可能在未来的Pandas版本中被弃用或更改。在较新版本的Pandas中,你可能更倾向于使用pandas.to_datetime函数,它也有一个infer_datetime_format参数,虽然它的行为可能与guess_datetime_format略有不同。

71-6、用法
71-6-1、数据准备
71-6-2、代码示例
# 71、pandas.tseries.api.guess_datetime_format函数
import pandas as pd
dt_str = '2024-07-17'
format_guess = pd.tseries.api.guess_datetime_format(dt_str)
print(format_guess)
71-6-3、结果输出
# 71、pandas.tseries.api.guess_datetime_format函数
# %Y-%m-%d
72、pandas.util.hash_array函数
72-1、语法
# 72、pandas.util.hash_array函数
pandas.util.hash_array(vals, encoding='utf8', hash_key='0123456789123456', categorize=True)
Given a 1d array, return an array of deterministic integers.

Parameters:
vals
ndarray or ExtensionArray
encoding
str, default ‘utf8’
Encoding for data & key when strings.

hash_key
str, default _default_hash_key
Hash_key for string key to encode.

categorize
bool, default True
Whether to first categorize object arrays before hashing. This is more efficient when the array contains duplicate values.

Returns:
ndarray[np.uint64, ndim=1]
Hashed values, same length as the vals.
72-2、参数

72-2-1、vals(必须)表示需要被哈希处理的输入数组,函数会遍历这个数组中的每个元素,并对其进行哈希处理。

72-2-2、encoding(可选,默认值为'utf8')指定数组中字符串元素的编码方式,如果数组中包含字符串,则这些字符串会根据此编码方式被转换为字节序列,然后再进行哈希处理。

72-2-3、hash_key(可选,默认值为'0123456789123456')提供了一个额外的密钥,用于在哈希过程中增加随机性,通过在哈希函数中加入这个密钥,可以增加哈希值的复杂性和安全性,尤其是在需要防止哈希碰撞的场景中。

72-2-4、categorize(可选,默认值为True)当此参数为True时,函数会首先尝试将输入数组中的元素分类(即,将相同的元素映射到相同的整数标签上),然后再对这些整数标签进行哈希处理,这可以在一定程度上减少哈希碰撞的可能性,并提高哈希过程的效率。如果输入数组已经是分类类型(Categorical dtype),则此参数的效果会更加明显。

72-3、功能

        给定一个一维数组(如NumPy数组或Pandas Series),返回该数组中每个元素的哈希值所组成的数组。

72-4、返回值

        返回一个与输入数组形状相同的一维NumPy数组,但其中的元素已被替换为对应元素的哈希值,这些哈希值是uint64类型的整数,它们代表了输入数组中每个元素的唯一(或尽可能唯一)标识符。

72-5、说明

        无

72-6、用法
72-6-1、数据准备
72-6-2、代码示例
# 72、pandas.util.hash_array函数
import pandas as pd
# 创建一个包含字符串的Series
s = pd.Series(['Jimmy', 'Bryce', 'Myelsa'])
# 计算每个字符串的哈希值
hashed_values = pd.util.hash_array(s.values)
# 输出哈希值数组
print(hashed_values)
72-6-3、结果输出 
# 72、pandas.util.hash_array函数
# [1382347394209841164 9798869407607568009 6426393181695770081]
73、pandas.util.hash_pandas_object函数
73-1、语法
# 73、pandas.util.hash_pandas_object函数
pandas.util.hash_pandas_object(obj, index=True, encoding='utf8', hash_key='0123456789123456', categorize=True)
Return a data hash of the Index/Series/DataFrame.

Parameters:
obj
Index, Series, or DataFrame
index
bool, default True
Include the index in the hash (if Series/DataFrame).

encoding
str, default ‘utf8’
Encoding for data & key when strings.

hash_key
str, default _default_hash_key
Hash_key for string key to encode.

categorize
bool, default True
Whether to first categorize object arrays before hashing. This is more efficient when the array contains duplicate values.

Returns:
Series of uint64, same length as the object.
73-2、参数

73-2-1、obj(必须)要进行哈希处理的Pandas对象(DataFrame或Series)。

73-2-2、index(可选,默认值为True)布尔值,指定是否将对象的索引也纳入哈希计算中。如果为True,则对象的索引也会被哈希处理;如果为False,则只考虑对象的数据部分。

73-2-3、encoding(可选,默认值为'utf8')字符串,用于指定在哈希处理过程中如何编码字符串类型的数据,这在处理包含非ASCII字符的数据时特别有用。

73-2-4、hash_key(可选,默认值为'0123456789123456')字符串,一个盐值(salt),用于增加哈希值的唯一性,通过添加这个盐值,即使两个Pandas对象在数据上完全相同,它们的哈希值也可能因为盐值的不同而不同,这有助于防止哈希碰撞,并提高哈希值的安全性。

73-2-5、categorize(可选,默认值为True)布尔值,如果为True,则在哈希处理之前,函数会尝试将对象中的分类数据(如pandas的Categorical类型)转换为整数编码,这样可以提高哈希处理的效率和一致性;如果为False,则直接使用原始数据进行哈希处理。

73-3、功能

        用于对Pandas对象(如DataFrame或Series)进行哈希处理,该函数对于需要将Pandas对象转换为哈希值以便进行快速比较或作为字典键等场景非常有用。

73-4、返回值

        函数返回一个NumPy数组,其中包含了对象中每一行(或元素,对于Series)的哈希值,这些哈希值可以用于比较、索引或其他需要唯一标识符的场景。

73-5、说明

73-5-1、快速比较:通过比较两个Pandas对象的哈希值,可以快速判断它们是否完全相同(注意,哈希冲突的可能性极低,但理论上存在)。

73-5-2、作为字典键:将Pandas对象哈希处理后,可以使用哈希值作为字典的键,以便快速查找或更新数据。

73-5-3、数据去重:在处理大量数据时,可以使用哈希值来识别并删除重复的行或记录。

73-6、用法
73-6-1、数据准备
73-6-2、代码示例
# 73、pandas.util.hash_pandas_object函数
# 73-1、对DataFrame进行哈希处理
import pandas as pd
# 创建一个简单的DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c'],
    'C': [True, False, True]
})
# 对DataFrame进行哈希处理,包括索引
hashes = pd.util.hash_pandas_object(df, index=True)
print("Hashes with index included:", hashes)
# 对DataFrame进行哈希处理,不包括索引
hashes_no_index = pd.util.hash_pandas_object(df, index=False)
print("Hashes without index:", hashes_no_index, end='\n\n')

# 73-2、对Series进行哈希处理
import pandas as pd
# 创建一个 Series
s = pd.Series([1, 2, 3, 4, 5])
# 对 Series 进行哈希处理
series_hashes = pd.util.hash_pandas_object(s)
print("Hashes for Series:", series_hashes)
# 注意:对于Series,通常没有索引(除非明确指定),但你可以通过reset_index()将其转换为DataFrame并包含索引
s_df = s.reset_index(drop=False)
s_df_hashes_with_index = pd.util.hash_pandas_object(s_df)
print("Hashes for Series as DataFrame with index:", s_df_hashes_with_index, end='\n\n')

# 73-3、处理包含浮点数的DataFrame
import pandas as pd
# 创建一个包含浮点数的DataFrame
df_floats = pd.DataFrame({
    'A': [1.0, 2.0, 3.0000000000001],  # 注意最后一个数有微小的精度差异
    'B': [4.0, 5.0, 6.0]
})
# 对DataFrame进行哈希处理
floats_hashes = pd.util.hash_pandas_object(df_floats)
print("Hashes for DataFrame with floats:", floats_hashes, end='\n\n')
# 注意:由于浮点数的精度问题,即使 '3.0' 和 '3.0000000000001' 在数值上接近,它们的哈希值也可能不同

# 73-4、对包含分类数据的DataFrame进行哈希处理
import pandas as pd
# 创建一个包含分类数据的DataFrame
df_categorical = pd.DataFrame({
    'A': pd.Categorical(['a', 'b', 'a', 'c']),
    'B': [1, 2, 3, 4]
})
# 对DataFrame进行哈希处理,包括分类数据的整数编码
categorical_hashes = pd.util.hash_pandas_object(df_categorical, categorize=True)
print("Hashes with categorical data (categorize=True):", categorical_hashes)
# 如果categorize=False,则直接对分类对象的字符串表示进行哈希处理
categorical_hashes_no_categorize = pd.util.hash_pandas_object(df_categorical, categorize=False)
print("Hashes with categorical data (categorize=False):", categorical_hashes_no_categorize, end='\n\n')

# 73-5、对包含时间戳的DataFrame进行哈希处理
import pandas as pd
# 创建一个包含时间戳的DataFrame
df_timestamps = pd.DataFrame({
    'Timestamp': pd.to_datetime(['2024-07-01', '2024-07-05', '2024-07-17'])
})
# 对DataFrame进行哈希处理
timestamp_hashes = pd.util.hash_pandas_object(df_timestamps)
print("Hashes for DataFrame with timestamps:", timestamp_hashes, end='\n\n')

# 73-6、处理具有NaN值的DataFrame
import pandas as pd
# 创建一个包含NaN值的DataFrame
df_nan = pd.DataFrame({
    'A': [1, 2, None, 4],
    'B': ['a', 'b', 'c', None]
})
# 对DataFrame进行哈希处理
nan_hashes = pd.util.hash_pandas_object(df_nan)
print("Hashes for DataFrame with NaN values:", nan_hashes, end='\n\n')
# 注意:NaN 值会以某种方式影响哈希值,但具体方式取决于Pandas的内部实现

# 73-7、对大型DataFrame进行哈希处理
import pandas as pd
import numpy as np
# 创建一个大型DataFrame(这里仅作为示例,实际中可能更大)
np.random.seed(0)
large_df = pd.DataFrame({
    'A': np.random.randint(0, 100, size=100000),
    'B': np.random.choice(['a', 'b', 'c', 'd'], size=100000),
    'C': np.random.rand(100000)
})
# 对大型DataFrame进行哈希处理(注意:这可能需要一些时间)
large_hashes = pd.util.hash_pandas_object(large_df, index=False)
print("Hashes for a large DataFrame (first 10):", large_hashes[:10])
73-6-3、结果输出
# 73、pandas.util.hash_pandas_object函数
# 73-1、对DataFrame进行哈希处理
# Hashes with index included: 0    9483444313420146699
# 1    5719781360446296993
# 2    9877900052590456950
# dtype: uint64
# Hashes without index: 0      485995293390257589
# 1     3005746743269222528
# 2    15997040775864825588
# dtype: uint64

# 73-2、对Series进行哈希处理
# Hashes for Series: 0    14639053686158035780
# 1     3869563279212530728
# 2      393322362522515241
# 3     4080319230603510727
# 4    13014484659661894915
# dtype: uint64
# Hashes for Series as DataFrame with index: 0     5967740633143088628
# 1     9280677857880118003
# 2     6253357580284104503
# 3     4295247446495588871
# 4    12355848007932281175
# dtype: uint64

# 73-3、处理包含浮点数的DataFrame
# Hashes for DataFrame with floats: 0    12179765616421863049
# 1     4850516111580897109
# 2    13664998175358214438
# dtype: uint64

# 73-4、对包含分类数据的DataFrame进行哈希处理
# Hashes with categorical data (categorize=True): 0    10448339489922407492
# 1      328955597323365005
# 2    17337560684877153397
# 3     7837014030697196839
# dtype: uint64
# Hashes with categorical data (categorize=False): 0    10448339489922407492
# 1      328955597323365005
# 2    17337560684877153397
# 3     7837014030697196839
# dtype: uint64

# 73-5、对包含时间戳的DataFrame进行哈希处理
# Hashes for DataFrame with timestamps: 0     5029448861734248502
# 1    15824968476515617805
# 2    16154582340151959443
# dtype: uint64

# 73-6、处理具有NaN值的DataFrame
# Hashes for DataFrame with NaN values: 0      390400230840112733
# 1     9079939592730820628
# 2    13397986763273461122
# 3    18293157628943714066
# dtype: uint64

# 73-7、对大型DataFrame进行哈希处理
# Hashes for a large DataFrame (first 10): 0     3741430234977074334
# 1    13815252830947086855
# 2     5536596816482122074
# 3     7459333729972558407
# 4    10226587178543578329
# 5    16985416363548347045
# 6     5210640794891753453
# 7      334407979408579242
# 8     3392106525313158311
# 9    17317895163462122340
# dtype: uint64

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神奇夜光杯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值