【问题标题】:Removing characters from column in pandas data frame从熊猫数据框中的列中删除字符
【发布时间】:2017-07-27 23:30:52
【问题描述】:

我的目标是 (1) 导入 Twitter JSON,(2) 提取感兴趣的数据,(3) 为感兴趣的变量创建 pandas 数据框。这是我的代码:

import json
import pandas as pd

tweets = []
for line in open('00.json'):
    try:
        tweet = json.loads(line)
        tweets.append(tweet)
    except:
        continue

# Tweets often have missing data, therefore use -if- when extracting "keys"

tweet = tweets[0]

ids = [tweet['id_str'] for tweet in tweets if 'id_str' in tweet] 
text = [tweet['text'] for tweet in tweets if 'text' in tweet]
lang = [tweet['lang'] for tweet in tweets if 'lang' in tweet]
geo = [tweet['geo'] for tweet in tweets if 'geo' in tweet]
place = [tweet['place'] for tweet in tweets if 'place' in tweet]

# Create a data frame (using pd.Index may be "incorrect", but I am a noob)
df=pd.DataFrame({'Ids':pd.Index(ids),
               'Text':pd.Index(text),
               'Lang':pd.Index(lang),
               'Geo':pd.Index(geo),
               'Place':pd.Index(place)})

# Create a data frame satisfying conditions:
df2 = df[(df['Lang']==('en')) & (df['Geo'].dropna())]

到目前为止,一切似乎都运行良好。

现在,Geo 的提取值导致以下示例:

df2.loc[1921,'Geo']
{'coordinates': [39.11890951, -84.48903638], 'type': 'Point'}

为了摆脱除方括号内的坐标之外的所有内容,我尝试使用:

df2.Geo.str.replace("[({':]", "") ### results in NaN
# and also this:
df2['Geo'] = df2['Geo'].map(lambda x: x.lstrip('{'coordinates': [').rstrip('], 'type': 'Point'')) ### results in syntax error

请告知仅获取坐标值的正确方法。

【问题讨论】:

    标签: json pandas twitter


    【解决方案1】:

    您问题中的以下行表明这是理解返回对象的基础数据类型的问题。

    df2.loc[1921,'Geo']
    {'coordinates': [39.11890951, -84.48903638], 'type': 'Point'}
    

    您在这里返回的是 Python 字典——不是字符串!如果你只想返回坐标值,你应该只使用'coordinates' 键来返回这些值,例如

    df2.loc[1921,'Geo']['coordinates']
    [39.11890951, -84.48903638]
    

    在这种情况下,返回的对象将是一个包含两个坐标值的 Python 列表对象。如果您只需要其中一个值,则可以对列表进行切片,例如

    df2.loc[1921,'Geo']['coordinates'][0]
    39.11890951
    

    此工作流程比将字典转换为字符串、解析字符串并重新捕获坐标值要容易得多。

    假设您要创建一个名为“geo_coord0”的新列,其中包含第一个位置的所有坐标(如上所示)。您可以使用类似以下的内容:

    df2["geo_coord0"] = [x['coordinates'][0] for x in df2['Geo']]
    

    这使用 Python 列表推导来遍历 df2['Geo'] 列中的所有条目,并且对于每个条目,它使用我们上面使用的相同语法来返回第一个坐标值。然后它将这些值分配给df2 中的新列。

    有关上述数据结构的更多详细信息,请参阅Python documentation on data structures。

    【讨论】:

    • 布莱恩,感谢您提供的解释。确实,我搞砸了你强调的问题。有了您的代码建议,问题现在就解决了。不过我肯定会挖掘有关数据结构的文档来了解它。
    • @kiton 很高兴我能帮上忙!如果您认为这可以解决此问题,请考虑 accepting my answer as a solution。
    猜你喜欢
    • 2018-03-23
    • 2021-08-12
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2021-09-25
    • 2021-09-10
    • 2016-01-29
    • 1970-01-01
    相关资源
    最近更新 更多