【问题标题】:How to correctly use .apply(lambda x:) on dataframe column如何在数据框列上正确使用 .apply(lambda x:)
【发布时间】:2019-02-13 20:47:44
【问题描述】:

我遇到的问题是我从df_modified['lat'] = df.coordinates.apply(lambda x: x[0]) 收到的错误它返回错误TypeError: 'float' object is not subscriptable。由于“坐标”已经是一个列表(参见 JSON SNIPPET),我试图使用 lambda 提取元素 [0] 并将其放置在名为“lat”的新列中,并将元素 [1] 放置在名为“长”。任何有关此问题的帮助将不胜感激。谢谢!

import pandas as pd
import json
import requests
from pandas.io.json import json_normalize

# READS IN JSON
source = requests.get('www.url.com')
data = json.loads(source.text)

# Flattens the JSON data since it had nested dictionaries
df = pd.io.json.json_normalize(data)

# Renamed "lat_long.coordinates" because the "." was confusing .apply() function
df.rename(columns={'lat_long.coordinates': 'coordinates'}, inplace=True)

# Created a new data frame with seleted columns
df_modified = df.loc[:, ['county_name', 'arrests', 'incident_count']]

# Attempt to create a new column "lat" and "long" and place the elemnts accordingly  i.e. [-75.802503,  41.820569]
df_modified['lat'] = df.coordinates.apply(lambda x: x[0])
df_modified['long'] = df.coordinates.apply(lambda x: x[1])

print(df_modified.head(30))

示例 JSON 片段

{
    ":@computed_region_amqz_jbr4": "587",
    ":@computed_region_d3gw_znnf": "18",
    ":@computed_region_nmsq_hqvv": "55",
    ":@computed_region_r6rf_p9et": "36",
    ":@computed_region_rayf_jjgk": "295",
    "arrests": "1",
    "county_code": "44",
    "county_code_text": "44",
    "county_name": "Mifflin",
    "fips_county_code": "087",
    "fips_state_code": "42",
    "incident_count": "1",
    "lat_long": {
      "type": "Point",
      "coordinates": [
        -77.620031,
        40.612749
      ]
    }

【问题讨论】:

  • 我认为需要将该列传递给应用函数df.apply( function(x): x['lat'][0] )。喜欢here
  • 上次我尝试使用 json 标准化 DF 时,我以为我的脑袋要爆炸了。
  • print(df['coordinates'].dtype) 的结果是什么
  • @kudeh 它返回object

标签: python pandas dataframe lambda apply


【解决方案1】:

你可以反过来做。在过滤列之前获取latlong

import pandas as pd

import json

with open('sample.json') as infile:
    data = json.load(infile)

df = pd.io.json.json_normalize(data)

df.rename(columns={'lat_long.coordinates': 'coordinates'}, inplace=True)
df['lat'] = df['coordinates'].apply(lambda x: x[0])
df['long'] = df['coordinates'].apply(lambda x: x[1])

# Created a new data frame with seleted columns
df_modified = df.loc[:, ['county_name', 'arrests', 'incident_count', 'lat', 
                         'long']]

【讨论】:

  • 仍然收到TypeError: 'float' object is not subscriptable
  • @prime90 我使用了您的确切 json sn-p,只是添加了一个额外的 } 以使其有效。您确定没有混淆 dfdf_modified?这段代码对我来说很好,所以如果我无法重现,我就无能为力了:/
  • 所以问题是我在坐标中缺少数据!我应该事先检查一下。您的解决方案完美运行。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 2016-12-28
  • 1970-01-01
相关资源
最近更新 更多