Pandas在函数ValueError中起作用

时间:2016-04-23 05:53:30

标签: python pandas

我尝试创建一个函数来帮助我创建一个GeoJSON文件。我尝试根据用户的性别和活动状态设置颜色属性。到目前为止我创建的函数:

import os
import pandas as pd
import numpy as np

def create_geojson(df): 

    def colour_func():
        if (df["Status"] == "Inactive"):                            #line 167
            return "#808080"
        elif (df["Status"] == "Active" and df["Gender"] == "Male"):
            return "#0000FF"
        else:
            return "#FF99FF"

    z = len(df)
    output = "C:\\Users\\Lukasz Obara\\Desktop\\Members.txt"
    f = open(output, "w")
    f.write('var Members = {\n\t' +
            '"type": "FeatureCollection",\n\t' +
            '"features": [')

    for x in range(0, z-1): 
        if (isinstance(df["Addr-Formatted"][x], str)):

            f.write('{\n\t\t"type": "Feature",\n\t\t' +
                '"geometry": {\n\t\t\t' +
                    '"type": "Point",\n\t\t\t' + 
                    '"coordinates": [%f, %f] \n\t\t' % (df["Lng"][x], 
                                                        df["Lat"][x]) +
                    '}, \n\t\t' +
                '"properties": {\n\t\t\t' +
                    '"Name": "%s, %s",\n\t\t\t' % (df['Member Name-First'][x],  
                                                   df['Member Name-Last'][x]) + 
                    '"Colour": "%s" \n\t\t' % colour_func() +
                "}\n\t" +                                        #line 205
            "}, ")

    f.close()
    os.rename(output, "C:\\Users\\Lukasz Obara\\Desktop\\Members.geojson")

我认为colour_func()应该是空的,因为它只是使用df中的create_geojson来返回适当的颜色(灰色,蓝色,粉红色),但我一直在:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Lukasz Obara\desktop\Test.py", line 205, in create_geojson
    "}\n\t"+
  File "C:\Users\Lukasz Obara\desktop\Test.py", line 167, in colour_func
    if (df["Status"] == "Inactive"):
  File "C:\Users\Lukasz Obara\Anaconda3\lib\site-packages\pandas\core\generic.py", line 887, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

1 个答案:

答案 0 :(得分:2)

使用&组合两个布尔系列而非and。您还需要在()

中对比较进行分组

所以,改变:

elif (df["Status"] == "Active" and df["Gender"] == "Male"):

成:

elif ((df["Status"] == "Active) & (df["Gender"] == "Male")):

修改

追溯有帮助。您需要指定索引:

def colour_func(ind):
    if df.loc[ind, "Status"] == "Inactive":
        return "#808080"
    elif df.loc[ind, "Status"] == "Active" and df.loc[ind, "Gender"] == "Male":
        return "#0000FF"
    else:
        return "#FF99FF"

然后使用索引z调用您的函数:

'"Colour": "%s" \n\t\t' % colour_func(z) +