Python日常用法—将列表信息写入到csv文件
1.模板
import csv
data_list = [{'皇马球员': 'C罗', '号码': '7', '国籍': '葡萄牙'},
{'皇马球员': '托尼··克罗斯', '号码': '8', '国籍': '德国'},
{'皇马球员': '马塞洛', '号码': '12', '国籍': '巴西'},
{'皇马球员': '卡里姆·本泽马', '号码': '9', '国籍': '法国'},]
f = open('hala_madrid.csv', 'w', encoding='utf-8')
csv_write = csv.writer(f)
csv_write.writerow(['皇马球员', '号码', '国籍'])
for data in data_list:
csv_write.writerow([data['皇马球员'], data['号码'], data['国籍']])
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f2e8741edb9869dfcdc3552250080030.png)
2.实例
import pandas as pd
import numpy as np
from collections import Counter
import csv
import pandas as pd
cloumn_names = []
all_cloumn_dict = []
all_counter = []
all_cloumn_value = []
data = pd.read_csv("model_jy_1.csv", header=None)
for i in data:
cloumn_names.append(i)
all_data = []
for i in cloumn_names:
nan_count = 0
print("********************* 第", cloumn_names.index(i) + 1, "列情况分布********************")
col_1 = data[i]
data_1 = np.array(col_1)
print("列名:", data_1[0])
print("列值:", data_1[1:])
data_2 = []
if data_1[0] == "C":
data_2 = ['99' if str(i) == 'nan' else i for i in list(data_1)]
if data_1[0] == "I":
temp = []
for j in list(data_1[1:]):
if str(j) != "nan":
temp.append(float(j))
mean_1 = round(np.mean(temp), 4)
data_2 = [str(mean_1) if str(i) == 'nan' else i for i in list(data_1)]
all_data.append(data_2)
print(all_data)
dataframe = pd.DataFrame({'M 0 ': all_data[ 0 ][1:] ,
'M 1 ': all_data[ 1 ][1:] ,
'M 2 ': all_data[ 2 ][1:] ,
'M 3 ': all_data[ 3 ][1:] ,
'M 4 ': all_data[ 4 ][1:] ,
'M 5 ': all_data[ 5 ][1:] , })
dataframe.to_csv(r"./model_jy_1_填充.csv", mode="a", index=False)
3.python 列表中的元素直接更改、替换
aaa=['马塞洛','阿扎尔','佩佩','拉莫斯']
bbb=['C罗' if i =='阿扎尔' else i for i in aaa]
bbb
结果:
['马塞洛','C罗','佩佩','拉莫斯']