簡體   English   中英

如何在數據框列上正確使用.apply(lambda x :)

[英]How to correctly use .apply(lambda x:) on dataframe column

我遇到的問題是Im從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
      ]
    }

您可以采用其他方法。 就拿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']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM