首页 > 解决方案 > raise ValueError('无法设置没有定义索引的框架' ValueError:

问题描述

我的代码出现以下错误

文件“C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py”,第 2519 行,在setitem self._set_item(key, value)

_set_item self._ensure_valid_index(value) 中的文件“C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py”,第 2584 行

文件“C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py”,第 2566 行,在 _ensure_valid_index raise ValueError('Cannot set a frame with no defined index'

ValueError:无法设置没有定义索引的框架和无法转换为系列的值

并且由于我仍在学习我在修复它时遇到了问题......我该怎么办?

import json
import pandas as pd
import matplotlib.pyplot as plt

tweets_data_path="C:/Users/prono/.spyder-py3/twitter_data.txt"

tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue

print(len(tweets_data))

tweets = pd.DataFrame()

tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
tweets['lang'] = map(lambda tweet: tweet['lang'], tweets_data)
tweets['country'] = map(lambda tweet: tweet['place']['country'] if tweet['place'] != None else None, tweets_data)

tweets_by_lang = tweets['lang'].value_counts()

fig, ax = plt.subplots()
ax.tick_params(axis='x', labelsize=15)
ax.tick_params(axis='y', labelsize=10)
ax.set_xlabel('Languages', fontsize=15)
ax.set_ylabel('Number of tweets' , fontsize=15)
ax.set_title('Top 5 languages', fontsize=15, fontweight='bold')
tweets_by_lang[:5].plot(ax=ax, kind='bar', color='red')

tweets_by_country = tweets['country'].value_counts()

fig, ax = plt.subplots()
ax.tick_params(axis='x', labelsize=15)
ax.tick_params(axis='y', labelsize=10)
ax.set_xlabel('Countries', fontsize=15)
ax.set_ylabel('Number of tweets' , fontsize=15)
ax.set_title('Top 5 countries', fontsize=15, fontweight='bold')
tweets_by_country[:5].plot(ax=ax, kind='bar', color='blue')

标签: pythonpython-3.xpandas

解决方案


推荐阅读