私の目標は、(1)Twitter JSONをインポートし、(2)関心のあるデータを抽出し、(3)関心のある変数のためのパンダデータフレームを作成することです。ここに私のコードです:パンダのデータフレームの列から文字を削除する
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())]
これまでのところ、すべてうまくいっているようです。今
、次の例のジオ結果のために抽出された値:
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
にご連絡ください:
df2.loc[1921,'Geo']
{'coordinates': [39.11890951, -84.48903638], 'type': 'Point'}
は、私が使用してみました二乗カッコ内の座標以外のすべてを取り除くために座標値のみを取得する正しい方法。
ブライアン、説明をいただきありがとうございます。確かに、私はあなたが強調した問題を混乱させました。あなたのコード提案では、問題は今解決されています。しかし、私は確かにそれについて学ぶためにデータ構造に関する文書を掘り下げます。 – kiton
@kitonうれしい!この問題を解決したと思えば[私の解答を受け入れる](http://stackoverflow.com/help/someone-answers)と考えてください。 – Brian