Dataframe не показывает источники Twitter из Android - PullRequest
0 голосов
/ 08 марта 2019

Я пытаюсь провести анализ аккаунта в твиттере, но у меня возникают проблемы с отображением источников из Android. То, что я сделал, было объединено два файла JSON, и я думаю, что я слил это правильно, но если я ошибся, вот код, который я использовал.

old_tweets = load_tweets("real_tweets/real_old_tweets.json")
print(len(old_tweets))  
for aLis1 in old_tweets:
    if aLis1 not in tweets:
        tweets.append(aLis1)

load_tweets - это пользовательская функция, которая просто открывает и загружает файл json с указанным путем

with open(path, "rb") as f:
    import json
    return json.load(f)

После объединения двух файлов json твитов я затем вызвал эту функцию, чтобы создать фрейм данных и очистить его, чтобы отобразить только ту информацию, которую я хочу.

df_tweets1 = pd.DataFrame(tweets)
df_tweets2 = df_tweets1[['id','created_at','source','full_text','retweet_count']]
df_tweets = df_tweets2.drop_duplicates('id', keep=False
df_tweets.set_index('id', inplace=True)
df_tweets = df_tweets.rename(columns={"created_at": "time", "full_text": "text"})
df_tweets["time"] = pd.to_datetime(df_tweets["time"])

Проблема в том, что когда я звоню df_tweets ["source"]. Unique () Я не вижу никаких твитов, исходящих от android

array(['<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>',
   '<a href="http://twitter.com/#!/download/ipad" rel="nofollow">Twitter for iPad</a>',
   '<a href="https://studio.twitter.com" rel="nofollow">Twitter Media Studio</a>',
   '<a href="https://studio.twitter.com" rel="nofollow">Media Studio</a>',
   '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>'],
  dtype=object)

Я сделал что-то не так при объединении двух наборов данных Twitter? Или я сделал что-то не так при попытке создать фрейм данных?

РЕДАКТИРОВАТЬ ** Вот пример выходных данных из real_old_tweets.json, чтобы дать представление о формате. Я собираюсь опубликовать только один, потому что в одном твите содержится много информации.

[{'created_at': 'Tue Oct 16 16:22:11 +0000 2018',
  'id': 1052233253040640001,
  'id_str': '1052233253040640001',
  'full_text': 'REGISTER TO https://url/0pWiwCHGbh! #MAGA?? https://url/ACTMe53TZU',
  'truncated': False,
  'display_text_range': [0, 44],
  'entities': {'hashtags': [{'text': 'MAGA', 'indices': [37, 42]}],
   'symbols': [],
   'user_mentions': [],
   'urls': [{'url': 'url/0pWiwCHGbh',
     'expanded_url': 'linkVote.GOP',
     'display_url': 'Vote.GOP',
     'indices': [12, 35]},
    {'url': 'url/ACTMe53TZU',
     'expanded_url': 'linktwitter.com/erictrump/status/1052174007708147714',
     'display_url': 'twitter.com/erictrump/stat…',
     'indices': [45, 68]}]},
  'source': '<a href="linktwitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>',
  'in_reply_to_status_id': None,
  'in_reply_to_status_id_str': None,
  'in_reply_to_user_id': None,
  'in_reply_to_user_id_str': None,
  'in_reply_to_screen_name': None,
  'user': {'id': 25073877,
   'id_str': '25073877',
   'name': 'Donald J. Trump',
   'screen_name': 'realDonaldTrump',
   'location': 'Washington, DC',
   'description': '45th President of the United States of America??',
   'url': 'url/OMxB0x7xC5',
   'entities': {'url': {'urls': [{'url': 'url/OMxB0x7xC5',
       'expanded_url': 'linkwww.Instagram.com/realDonaldTrump',
       'display_url': 'Instagram.com/realDonaldTrump',
       'indices': [0, 23]}]},
    'description': {'urls': []}},
   'protected': False,
   'followers_count': 55165024,
   'friends_count': 47,
   'listed_count': 94709,
   'created_at': 'Wed Mar 18 13:46:38 +0000 2009',
   'favourites_count': 25,
   'utc_offset': None,
   'time_zone': None,
   'geo_enabled': True,
   'verified': True,
   'statuses_count': 39296,
   'lang': 'en',
   'contributors_enabled': False,
   'is_translator': False,
   'is_translation_enabled': True,
   'profile_background_color': '6D5C18',
   'profile_background_image_url': 'linkabs.twimg.com/images/themes/theme1/bg.png',
   'profile_background_image_url_https': 'linkabs.twimg.com/images/themes/theme1/bg.png',
   'profile_background_tile': True,
   'profile_image_url': 'linkpbs.twimg.com/profile_images/874276197357596672/kUuht00m_normal.jpg',
   'profile_image_url_https': 'linkpbs.twimg.com/profile_images/874276197357596672/kUuht00m_normal.jpg',
   'profile_banner_url': 'linkpbs.twimg.com/profile_banners/25073877/1539493274',
   'profile_link_color': '1B95E0',
   'profile_sidebar_border_color': 'BDDCAD',
   'profile_sidebar_fill_color': 'C5CEC0',
   'profile_text_color': '333333',
   'profile_use_background_image': True,
   'has_extended_profile': False,
   'default_profile': False,
   'default_profile_image': False,
   'following': False,
   'follow_request_sent': False,
   'notifications': False,
   'translator_type': 'regular'},
  'geo': None,
  'coordinates': None,
  'place': None,
  'contributors': None,
  'is_quote_status': True,
  'quoted_status_id': 1052174007708147714,
  'quoted_status_id_str': '1052174007708147714',
  'quoted_status_permalink': {'url': 'url/ACTMe53TZU',
   'expanded': 'linktwitter.com/erictrump/status/1052174007708147714',
   'display': 'twitter.com/erictrump/stat…'},
  'quoted_status': {'created_at': 'Tue Oct 16 12:26:46 +0000 2018',
   'id': 1052174007708147714,
   'id_str': '1052174007708147714',
   'full_text': 'Friends: Quick reminder that today is that last day to register to vote in Oregon, Kansas, Louisiana, West Virginia, New Jersey and Maryland. It is very quick and easy - simply go to url/GE5BO5ONN1! Let’s #MakeAmericaGreatAgain ??????',
   'truncated': False,
   'display_text_range': [0, 243],
   'entities': {'hashtags': [{'text': 'MakeAmericaGreatAgain',
      'indices': [214, 236]}],
    'symbols': [],
    'user_mentions': [],
    'urls': [{'url': 'url/GE5BO5ONN1',
      'expanded_url': 'linkwww.Vote.GOP',
      'display_url': 'Vote.GOP',
      'indices': [183, 206]}]},
   'source': '<a href="linktwitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>',
   'in_reply_to_status_id': None,
   'in_reply_to_status_id_str': None,
   'in_reply_to_user_id': None,
   'in_reply_to_user_id_str': None,
   'in_reply_to_screen_name': None,
   'user': {'id': 39349894,
    'id_str': '39349894',
    'name': 'Eric Trump',
    'screen_name': 'EricTrump',
    'location': '',
    'description': "Executive Vice President of The @Trump Organization. Husband to @LaraLeaTrump. Large advocate of @StJude Children's Research Hospital. #MakeAmericaGreatAgain",
    'url': 'url/uwwNiWyamR',
    'entities': {'url': {'urls': [{'url': 'url/uwwNiWyamR',
        'expanded_url': 'linkwww.Trump.com',
        'display_url': 'Trump.com',
        'indices': [0, 23]}]},
     'description': {'urls': []}},
    'protected': False,
    'followers_count': 2191617,
    'friends_count': 715,
    'listed_count': 5736,
    'created_at': 'Mon May 11 21:42:30 +0000 2009',
    'favourites_count': 8638,
    'utc_offset': None,
    'time_zone': None,
    'geo_enabled': True,
    'verified': True,
    'statuses_count': 5601,
    'lang': 'en',
    'contributors_enabled': False,
    'is_translator': False,
    'is_translation_enabled': False,
    'profile_background_color': '000000',
    'profile_background_image_url': 'linkabs.twimg.com/images/themes/theme1/bg.png',
    'profile_background_image_url_link': 'linkabs.twimg.com/images/themes/theme1/bg.png',
    'profile_background_tile': True,
    'profile_image_url': 'linkpbs.twimg.com/profile_images/974045997268529152/R0CuVYHM_normal.jpg',
    'profile_image_url_link': 'linkpbs.twimg.com/profile_images/974045997268529152/R0CuVYHM_normal.jpg',
    'profile_banner_url': 'linkpbs.twimg.com/profile_banners/39349894/1516709628',
    'profile_link_color': '116AB8',
    'profile_sidebar_border_color': '000000',
    'profile_sidebar_fill_color': '616161',
    'profile_text_color': '000000',
    'profile_use_background_image': True,
    'has_extended_profile': False,
    'default_profile': False,
    'default_profile_image': False,
    'following': False,
    'follow_request_sent': False,
    'notifications': False,
    'translator_type': 'none'},
   'geo': None,
   'coordinates': None,
   'place': None,
   'contributors': None,
   'is_quote_status': False,
   'retweet_count': 1945,
   'favorite_count': 3828,
   'favorited': False,
   'retweeted': False,
   'possibly_sensitive': False,
   'lang': 'en'},
  'retweet_count': 5415,
  'favorite_count': 16565,
  'favorited': False,
  'retweeted': False,
  'possibly_sensitive': False,
  'lang': 'en'},

1 Ответ

1 голос
/ 09 марта 2019

Я предполагаю, что у вас есть "андроидные" источники, и у меня нет четкого представления о том, как выглядят ваши данные и какова связь между "id" и источником. Сказав это, есть ошибка, когда вы готовите свои данные. Вы отбрасываете все дубликаты.

Например:

>>> import pandas as pd
>>> df = pd.DataFrame(data={'col1':[1,2,2],'col2':[3,4,3],'col3':[1,4,1]})
>>> df
   col1  col2  col3
0     1     3     1
1     2     4     4
2     2     3     1
>>> df.drop_duplicates('col1',keep=False)
   col1  col2  col3
0     1     3     1

В приведенном выше коде вы можете увидеть, что он удаляет все повторяющиеся строки, если вы используете "keep = False".

>>> df.drop_duplicates('col1',keep='first')
   col1  col2  col3
0     1     3     1
1     2     4     4

Вместо этого используйте keep = 'first' или keep = 'last' и посмотрите, есть ли улучшения. Кроме того, было бы здорово, если бы я мог получить больше информации о данных, чтобы выяснить, где они идут не так.

EDIT

Через некоторое время я взял ваш объект JSON и сохранил его в файле "me.json" в формате:

[{},{}]

Где источником первого объекта является iPhone, а источником второго объекта является Android. Я использовал ваш код для загрузки данных:

Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> import json
>>> with open('me.json','rb') as file:
...     json_list = json.load(file)
... 
>>> len(json_list)
2
>>> df = pd.DataFrame(json_list)
>>> df1 = df[['id','source']]
>>> df1['source'].value_counts()
<a href="linktwitter.com/download/Android" rel="nofollow">Twitter for Android</a>    1
<a href="linktwitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>      1
Name: source, dtype: int64

В приведенном выше выводе вы видите, что я могу видеть "Android" . Мой вывод заключается в том, что в ваших данных может быть вообще нет "Android" , в столбце df ['source'].

Пожалуйста, смотрите внимательно, поскольку в каждом объекте JSON есть два "источника" ключа, один ключ находится внутри "quoted_status" . Есть вероятность, что вы могли видеть «Android» в этом ключе.

...