Python教程

Python数据分析小技巧【01】

本文主要是介绍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]

 

这篇关于Python数据分析小技巧【01】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!