python-3.x 无法将具有多列的DataFrame设置为单列

cdmah0mi  于 2023-04-13  发布在  Python
关注(0)|答案(1)|浏览(1589)

我是使用pandas的新手,我试图修复我的脚本的最后一部分。当调用以下函数时,我得到错误:

  1. ValueError: Cannot set a DataFrame with multiple columns to the single column place_name
  1. def get_place_name(latitude, longitude):
  2. location = geolocator.reverse(f"{latitude}, {longitude}", exactly_one=True)
  3. if location is None:
  4. return None
  5. else:
  6. return location.address

此函数从此处调用:

  1. metadata_df = extract_metadata(dir_path)
  2. print("[+] Metadata extracted from all image files")
  3. print(metadata_df.columns)
  4. geolocator = Nominatim(user_agent="exif_location")
  5. metadata_df['place_name'] = metadata_df.apply(
  6. lambda row: get_place_name(
  7. row['gps_latitude'], row['gps_longitude']),
  8. axis=1)

任何帮助或建议将不胜感激:)

w6mmgewl

w6mmgewl1#

你的代码对我来说很好用(Pandas1.5.3,Geopy 2.3.0):

  1. df = pd.DataFrame({'lat': [34.053691, 40.712728],
  2. 'lon': [-118.242766, -74.006015]})
  3. geolocator = Nominatim(user_agent='MyApp')
  4. df['place_name'] = df.apply(lambda x: get_place_name(x['lat'], x['lon']), axis=1)
  5. print(df)

输出

  1. lat lon place_name
  2. 0 34.053691 -118.242766 Los Angeles City Hall, 200, North Spring Stree...
  3. 1 40.712728 -74.006015 New York City Hall, 260, Broadway, Lower Manha...

我不明白为什么你的函数试图返回一个有多列的 Dataframe 。如果你这样做,你的错误是可重复的:

  1. df['place_name'] = df[['lat', 'lon']]
  2. ...
  3. ValueError: Cannot set a DataFrame with multiple columns to the single column place_name
展开查看全部

相关问题