|
发表于 2021-12-5 18:24:37
From FishC Mobile
|
显示全部楼层
|阅读模式
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
人均国内生产总值(元)
8717
9506
10666
12487
14368
16738
20494
24100
26180
30808
36277
39771
43497
46912
49922
53783
59592
65534
70328
72000
这是经济数据.csv文件中的一列如何
读取“经济数据.csv”,判断"人均国内生产总值(元)“是否大于20000,如果大于则设置为”是“,否则设置为”否“,新建一列保存结果
我没有权限贴文件,谢谢各位大佬!
如果只有一列数据,假设数据如你所贴出的,代码如下: - import csv
- with open('data2.csv', 'r', encoding='utf-8') as csvfile:
- reader = csv.reader(csvfile)
- data = list(reader)
- with open('result2.csv', 'w', encoding='utf-8', newline='') as csvfile:
- writer = csv.writer(csvfile)
- for line in data:
- if int(line[0]) > 20000:
- line.append('是')
- else:
- line.append('否')
- writer.writerow(line)
复制代码
假如数据有多列,分割符为逗号,假设数据如下(其他数据用数字代替了):
- 8717,0,1
- 9506,0,1
- 10666,0,1
- 12487,0,1
- 14368,0,1
- 16738,0,1
- 20494,0,1
- 24100,0,1
- 26180,0,1
- 30808,0,1
- 36277,0,1
- 39771,0,1
- 43497,0,1
- 46912,0,1
- 49922,0,1
- 53783,0,1
- 59592,0,1
- 65534,0,1
- 70328,0,1
- 72000,0,1
复制代码
那么代码如下:
- import csv
- with open('data.csv', 'r', encoding='utf-8') as csvfile:
- reader = csv.reader(csvfile, delimiter=',')
- data = list(reader)
- with open('result.csv', 'w', encoding='utf-8', newline='') as csvfile:
- writer = csv.writer(csvfile)
- for line in data:
- if int(line[0]) > 20000:
- line.append('是')
- else:
- line.append('否')
- writer.writerow(line)
复制代码
|
|