Python数据分析小技巧【01】
作者:互联网
1.将字符串翻转
my_Str = "ABCDE"
r_Str = my_Str[::-1]
print(r_Str)
output:
EDCBA
2.英文单词首字母大写
my_str = "my name is xiao ming"
# 通过title()来实现首字母大写
new_str = my_str.title()
print(new_str)
output:
My Name Is Xiao Ming
3.字符串去掉重复值
my_str = "aabbbbbccccddddeeeff"
# 通过set()来进行去重
temp_set = set(my_str)
print(temp_set)
# 通过join()来进行连接
new_str = ''.join(temp_set)
print(new_str)
output:
{'b', 'f', 'd', 'e', 'c', 'a'}
bfdeca
4.拆分字符串
str_1 = "my name is li hua"
str_2 = "zhangwei, wanglei, xiaoming"
# 默认的分隔符是空格,来进行拆分
print(str_1.split())
# 根据分隔符","来进行拆分
print(str_2.split(','))
output:
['my', 'name', 'is', 'li', 'hua']
['zhangwei', ' wanglei', ' xiaoming']
5.将列表中的字符串连接起来
my_dict = ['my', 'name', 'is', 'li', 'hua']
# 通过空格和join来连词成句
print(' '.join(my_dict))
output:
my name is li hua
6.查看列表中各元素出现的次数
from collections import Counter
mylist = ["a","b","b","c","c","c","d","d","d","d"]
count = Counter(mylist)
# 输出count的元素,统计出现的次数
print("count",count)
# 单独的“b”元素出现的次数
print("count['b']",count['b'])
# 出现频率最多的元素
print(count.most_common(1))
output:
count Counter({'d': 4, 'c': 3, 'b': 2, 'a': 1})
count['b'] 2
[('d', 4)]
7.合并两个字典
mydict_1 = {'a': 3, 'b': 4}
mydict_2 = {'c': 4, 'd': 5}
# 方法一
combined_dict = {**mydict_1, **mydict_2}
print("combined_dict", combined_dict)
# 方法二
mydict_1.update(mydict_2)
print("mydict_1", mydict_1)
# 方法三
print("mydict_1", dict(mydict_1.items() | mydict_2.items()))
output:
combined_dict {'a': 3, 'b': 4, 'c': 4, 'd': 5}
mydict_1 {'a': 3, 'b': 4, 'c': 4, 'd': 5}
mydict_1 {'a': 3, 'd': 5, 'b': 4, 'c': 4}
8.查看程序运行的时间
import time
start_time = time.time()
########################
#具体的程序
for i in range(1,10):
for j in range(1,50):
print("i*j",i*j)
########################
end_time = time.time()
time_taken_in_micro = end_time- start_time
print(time_taken_in_micro)
output:
0.015621423721313477
9.数组的扁平化
a = [[1,3],[2,4],[3,5]]
a = np.array(a)
print(a.flatten())
output:
[1 3 2 4 3 5]
标签:数据分析,01,Python,my,str,time,print,output,mydict 来源: https://blog.csdn.net/Bigboss7/article/details/118855820