python - 在 Python 中,如何在创建的 csv 文件中插入一个附加字段,该文件根据查询结果对字段内容具有 elseif 条件?
问题描述
这是从我的查询中获取数据并将其打包到 csv 文件中的 python 代码。
...
col_headers = [ i[0] for i in cursor.description ]
rows = [ list(i) for i in cursor.fetchall()]
df = pd.DataFrame(rows, columns=col_headers)
df.to_csv("PremiseCPE.csv", index=False)
for row in cursor.fetchall():
print (row)
...
传入的数据在列中。我需要添加一个名为“地标”的附加列(#6)。然后,我需要根据名为 cpeStatus 的 #3 列中的值,为数据库的每个输出在新列行中添加值。以下是我在创建 kml 文件时尝试的查询结构类型:
...
iif (row[4]) = 'Off', (row[6]) = "http://maps.google.com/mapfiles/kml/shapes/forbidden.png"
ElseIf (row[4]) = 'Active', (row[6]) = "http://maps.google.com/mapfiles/kml/shapes/ranger_station.png"
ElseIf (row[4]) = 'Ready, (row[6]) = "http://maps.google.com/mapfiles/kml/shapes/mechanic.png"
ElseIf (row[4]) = 'Alarm', (row[6]) = "http://maps.google.com/mapfiles/kml/shapes/caution.png"
ElseIf (row[4]) = 'Null', (row[6]) = "http://maps.google.com/mapfiles/kml/shapes/white_bubble.png"
End If
...
目标是尝试在 csv 文件级别运行它。
任何人都可以帮忙吗?
解决方案
正如@MattDMo 所说,您需要在写入 CSV 之前在数据框中执行此操作。另外,我更喜欢字典查找而不是if...elif...else
python 中的 long。最后,我建议使用pd.read_sql来查询数据库并创建 df。
import pandas as pd
col_headers = ['col1', 'cols2', 'yada', 'cpeStatus', 'murgatroyd', 'noimagination']
rows = [[1, 2, 3, 'Off', 'is', 42],
[2, 4, 42, 'Active', 'the', 42],
[3, 9, 12, 'Ready', 'best', 42],
[4, 16, 20, 'Off', 'name', 42],
[5, 25, 30, 'Alarm', 'no', 42],
[6, 36, 42, 'Null', 'its', 42],
[7, 49, 56, 'Danger', 'not', 42],]
df = pd.DataFrame(rows, columns=col_headers)
plmks = {'Off': "forbidden.png",
'Active': "ranger_station.png",
'Ready': "mechanic.png",
'Alarm': "caution.png",
'Null': "white_bubble.png"}
df['Placemarks'] = [plmks.get(st, "headslap.png") for st in df['cpeStatus']]
print(df)
df.to_csv("PremiseCPE.csv", index=False)
产生以下df:
0 1 2 3 Off is 42 forbidden.png
1 2 4 42 Active the 42 ranger_station.png
2 3 9 12 Ready best 42 mechanic.png
3 4 16 20 Off name 42 forbidden.png
4 5 25 30 Alarm no 42 caution.png
5 6 36 42 Null its 42 white_bubble.png
6 7 49 56 Danger not 42 headslap.png
和以下 CSV:
col1,cols2,yada,cpeStatus,murgatroyd,noimagination,Placemarks
1,2,3,Off,is,42,forbidden.png
2,4,42,Active,the,42,ranger_station.png
3,9,12,Ready,best,42,mechanic.png
4,16,20,Off,name,42,forbidden.png
5,25,30,Alarm,no,42,caution.png
6,36,42,Null,its,42,white_bubble.png
7,49,56,Danger,not,42,headslap.png
推荐阅读
- python - 为什么在一种情况下更改熊猫数据框列中的值很快,而在另一种情况下更改速度很慢?
- list - 如何防止 Markdown 的列表吃空格?
- flutter - 颤抖每24小时自动更新一次Firebase的最佳方法是什么?
- angular - Angular 7响应式表单如何获取选定值的文本而不是下拉列表表单控件中的值
- elasticsearch - 文本中的短语之间有多少个单词?
- python - Maya python 地形生成器
- sonarqube - SonarQube 无法在 linux 中启动
- r - 将两个边距添加到 facet_grid 但不是组合
- oracle - 为 oracle db 创建 lucene 索引 - 性能
- java - Log4j 不在 Linux 服务器上工作,但在 Eclipse (Windows) 上工作