2020-08-27

Python字符串操作与数据类型解析
本文详细介绍了Python中字符串的常见操作,如替换、分割和判断数字字符串,并深入探讨了字典作为映射类型的特点,对比序列类型,阐述了可变与不可变类型的区别及其判断方法。

python学习

s = 'loveLOVElooi'
s1 = s.replace('0','j')
s2 = s.replace('o'and'l','j'and'm')
print(s)
print(s1)
print(s2)


s4 = 'I love LOL'
s5 = s4.split(' ')
print(s4)
print(s5)


s6 = ' I love China'
s7 = s6.lstrip()
print(s6)
print(s7)


def isdigit0(string):
    lst = list(string)
    for i in lst:
        if not (ord(i)>=48 and ord(i)<=57):
            return False
    return True

def isdigit1(string):
    for i in string:
        if not (ord(i) >= 48 and ord(i) <= 57):
            return False
    return True

def isdigit2(string):
    for index in range(len(string)):
        if not(ord(string[index])>=48 and ord(string[index])<=57):
            return False
    return True

s8 = '01597949'
s9 = 'dasd1551453'
print(isdigit0(s8))
print(isdigit0(s9))
print(isdigit1(s8))
print(isdigit1(s9))
print(isdigit2(s8))
print(isdigit2(s9))
loveLOVElooi
loveLOVElooi
moveLOVEmooi
I love LOL
['I', 'love', 'LOL']
 I love China
I love China
True
False
True
False
True
False

2.字典
(1)可变类型与不可变类型
序列是以连续的整数为索引,与此不同的是,字典以"关键字"为索引,关键字可以是任意不可变类型,通常用字符串或数值。
字典是Python里唯一的一个映射类型,字符串、元组、列表属于序列类型。

判断数据类型是否可变的方法
【1】利用id(X)函数,如果前后X的值一样,则X可变,如果不一样,则不可变
【2】用hash(X),只要不报错,证明X可被哈希,即不可变,反过来不可被哈希,即可变。

ValueError Traceback (most recent call last) /tmp/ipykernel_128/149580382.py in <cell line: 0>() 5 6 # 创建带类型声明的时间模板 ----> 7 d2 = pd.DataFrame({ 8 ‘年’: time_template.year.astype(int), 9 ‘月’: time_template.month.astype(int), /usr/local/lib/python3.11/dist-packages/pandas/core/frame.py in init(self, data, index, columns, dtype, copy) 776 elif isinstance(data, dict): 777 # GH#38939 de facto copy defaults to False only in non-dict cases –> 778 mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager) 779 elif isinstance(data, ma.MaskedArray): 780 from numpy.ma import mrecords /usr/local/lib/python3.11/dist-packages/pandas/core/internals/construction.py in dict_to_mgr(data, index, columns, dtype, typ, copy) 501 arrays = [x.copy() if hasattr(x, “dtype”) else x for x in arrays] 502 –> 503 return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy) 504 505 /usr/local/lib/python3.11/dist-packages/pandas/core/internals/construction.py in arrays_to_mgr(arrays, columns, index, dtype, verify_integrity, typ, consolidate) 112 # figure out the index, if necessary 113 if index is None: –> 114 index = _extract_index(arrays) 115 else: 116 index = ensure_index(index) /usr/local/lib/python3.11/dist-packages/pandas/core/internals/construction.py in _extract_index(data) 688 f"length {len(index)}" 689 ) –> 690 raise ValueError(msg) 691 else: 692 index = default_index(lengths[0]) ValueError: array length 32881 does not match index length 0 原代码为: 生成时间模板 start_date = merged_data[‘DATE OCC’].min() end_date = merged_data[‘DATE OCC’].max() time_template = pd.date_range(start=start_date, end=end_date, freq=‘H’) 创建带类型声明的时间模板 d2 = pd.DataFrame({ ‘年’: time_template.year.astype(int), ‘月’: time_template.month.astype(int), ‘日’: time_template.day.astype(int), ‘小时’: time_template.hour.astype(int), ‘AREA’: pd.Series(dtype=‘object’), ‘AREA NAME’: pd.Series(dtype=‘object’) }) 填充空值 d2[‘AREA’] = d2[‘AREA’].fillna(‘’) d2[‘AREA NAME’] = d2[‘AREA NAME’].fillna(‘’) 合并 d2 和 merged_data,只保留匹配的时间段 d2 = pd.merge(d2, merged_data, on=[‘年’, ‘月’, ‘日’, ‘小时’], how=‘inner’) 查看结果 print(d2) merged_data.head() DR_NO Date Rptd DATE OCC TIME OCC AREA AREA NAME Rpt Dist No \ 0 200815333 2020-10-15 2020-10-15 2000 8 West LA 814 1 200914052 2020-08-27 2020-08-27 1255 9 Van Nuys 935 2 200810920 2020-06-20 2020-06-20 1000 8 West LA 841 3 200811087 2020-06-24 2020-06-23 2200 8 West LA 898 4 200104054 2020-01-02 2020-01-01 2330 1 Central 135 Part 1-2 Crm Cd Crm Cd Desc ... Year Month Day Hour \ 0 2 624 BATTERY - SIMPLE ASSAULT ... 2020 10 15 20 1 2 624 BATTERY - SIMPLE ASSAULT ... 2020 8 27 12 2 2 624 BATTERY - SIMPLE ASSAULT ... 2020 6 20 10 3 2 624 BATTERY - SIMPLE ASSAULT ... 2020 6 23 22 4 2 624 BATTERY - SIMPLE ASSAULT ... 2020 1 1 23 Time Period Day of Week Date Is Holiday 天气 季节 0 20-21 星期四 2020-10-15 0 晴 秋季 1 12-13 星期四 2020-08-27 0 晴 夏季 2 10-11 星期六 2020-06-20 0 晴 夏季 3 22-23 星期二 2020-06-23 0 阴 夏季 4 23-24 星期三 2020-01-01 1 阴 冬季 要求:最终只保留d2 和 merged_data 中匹配的时间段,没有对应或匹配上的直接删除对应行,只保留有merged_data对应时间段的行。注意存在d2文件不需要创建,d2中原先存在的列为:‘年’, ‘月’, ‘日’, ‘小时’, ‘Case Count’, dtype=‘object’, 但在代码不要遗漏了Case Count列,修改代码完成将merged_data中的天气等特征信息,追加到d2
06-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值