在for循环内为pandas数据框创建新列

时间:2017-03-16 01:18:52

标签: pandas

有一个包含3列A,B和C

的pandas数据帧
Id  Date        Latitude     Longitude
9497        2017-03-03  44.149147   -70.230300
914         2017-02-27  38.832256   -104.761086

我想遍历数据框并在for循环中创建一个新列。

我尝试使用以下代码,但是我收到错误“未定义列”。任何建议都会非常有用。

for index,row in df2.iterrows():
  value = Geohash.encode(row['Latitude'],row['Longitude'], precision=8)
  df2.set_value(index,'Geohash',value)

1 个答案:

答案 0 :(得分:2)

在循环之前创建列:

df2['Geohash'] = -1 # or np.nan or whatever

for index,row in df2.iterrows():
      value = Geohash.encode(row['Latitude'],row['Longitude'], precision=8)
      df2.set_value(index,'Geohash',value)
相关问题