0

这是从我的查询中获取数据并将其打包到 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 文件级别运行它。

任何人都可以帮忙吗?

4

1 回答 1

0

正如@MattDMo 所说,您需要在写入 CSV 之前在数据框中执行此操作。另外,我更喜欢字典查找而不是if...elif...elsepython 中的 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
于 2020-09-29T22:31:27.140 回答