我正在尝试根据查找表将数据添加到 shapefile。因此,shapefile 和查找表都具有土地利用、雨水和土壤属性的值,并且查找表还具有我想根据土地利用/雨水/土壤值添加到 shapefile 中的其他变量的值。这是我在 R 中非常有信心做的事情,但它需要在 python 中,因为这是 QGIS 中使用的语言,而且我对 python 很陌生。
目前,我通过在 python 中使用 pandas 数据框来简化问题:
import pandas as pd
#1. sample data
landuses = ['Pasture', 'Pasture', 'Stonefruit', 'Vineyard']
soils = [90, 120, 150, 90]
rainfalls = [350, 450, 550, 650]
sample_dict = {'landuse' : landuses,
'soil' : soils,
'rain' : rainfalls}
sample_df = pd.DataFrame(sample_dict)
print(sample_df)
# 2. lookup table data
v1 = [1,2,3,4]
v2 = [5,6,7,8]
v3 = [9,10,11,12]
lookup_dict = {'landuse' : landuses,
'soil' : soils,
'rain' : rainfalls,
'v1' : v1,
'v2' : v2,
'v3' : v3}
lookup_df = pd.DataFrame(lookup_dict)
print(lookup_df)
显然,这两个表都会有更多的数据,但希望你能明白。所以我想要v1
,v2
和v3
intosample_df
基于匹配所有landuse
,soil
和的值rain
。我已经尝试了各种解决方案,涉及np.logical_and()
和其他一些类似的事情,并且已经能够使它适用于简化版本,但不能为表格增加价值。到目前为止,我不会再让你厌烦我失败尝试的细节,但我认为最好的解决方案(至少对于我的 python 编程水平)将是创建一个索引字符串,将landuse
,rain
和soil
值组合起来基于此的表之间的行和匹配。例如,第一行的字符串sample_df
是'Pasture 90 350'
,我可以将其添加到两个表中,然后用作索引。
但是,当我尝试使用以下方法创建索引字符串时:
sample_df['index'] = sample_df['landuse'] + " " + str(sample_df['rain']) + " " + str(sample_df['soil'])
它将所有值soil
合并rain
到字符串中,这不是我想要的。
而且,当我使用简单的数字索引键进行下一步的测试运行时:
sample_df['index1'] = [1,2,3,4]
lookup_df['index1'] = [1,2,3,4]
sample_df['v1'] = lookup_df[lookup_df['index1'] == sample_df['index1']]
print(sample_df)
该lookup_df[lookup_df['index1'] == sample_df['index1']]
部分独立工作,但分配不工作。
谁能帮我?我猜该解决方案涉及使用.assign
(我理解它是mutate()
R 中的 python 等价物),但我无法弄清楚。提前感谢您的任何帮助!