![](/img/trans.png)
[英]TypeError : list indices must be integers or slices, not str when trying to plot
[英]trying to use groupby() function but keep getting "TypeError: list indices must be integers or slices, not str"
編輯:我在“event_id”前面添加了“columns”,因為當我之前僅使用“event_id”嘗試代碼時,我一直收到“keyerror:“event_id”。我現在去掉了“columns”代碼,但是我仍然得到相同的keyerror;我檢查了“event_id”,它被python識別為一列……有什么建議嗎?
我正在嘗試根據“event_id”將 df_userpolice 匯總到類別中,然后匯總每個 event_id 的所有其他數字(每個 event_id 的平均粉絲數等); 然后我需要將它與較小的數據幀 df_eventpolice 合並。 我已將 event_id 中的每一行都更改為 excel 中的整數,但由於某種原因它仍然無法正常工作,這是我的代碼:
import pandas as pd
import dateutil
df_userpolice = pd.read_csv(filepath_or_buffer='userpolice.csv', error_bad_lines=False)
df_eventpolice = pd.read_csv(filepath_or_buffer='eventpolice.csv', index_col = 0)
columns = ['event_id', 'city_indiv', 'post_id_indiv', 'content_indiv', 'content_media', 'is_same_event', 'post_id_media', 'prov_code', 'date_indiv', 'geolocation', 'issue_type_indiv', 'followers_count', 'fan_count', 'gender', 'status_count', 'issue_type_words_indiv', 'action_form_indiv', 'action_form_words_indiv', 'username', 'city_media', 'uid', 'verified', 'self_description', 'verified_type', 'refined', 'date_media', 'issue_type_media', 'issue_type_words_media', 'action_form_media', 'action_form_words_media']
print(df_userpolice)
for row in df_userpolice:
print(row)
for row in df_eventpolice:
print(row)
df_userpolice.groupby['event_id'].groups.keys() <------this is where the error happens
但我不斷收到以下錯誤:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-38-75f25f3b87eb> in <module>()
15 # Drop NA values, listing the converted columns explicitly
16 # so NA values in other columns aren't dropped
---> 17 df.dropna(subset = ['event_id'])
18
19
/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in dropna(self, axis, how, thresh, subset, inplace)
4746 check = indices == -1
4747 if check.any():
-> 4748 raise KeyError(list(np.compress(check, subset)))
4749 agg_obj = self.take(indices, axis=agg_axis)
4750
KeyError: ['event_id']
我真的不知道我哪里錯了。
問題在於“列['event_id']”。
這里的列類型是列表,列表項可以通過其索引訪問,但不像 columns['event_id']。
我希望您在這里的目的是創建一個字典“列”,但您聲明“列”的方式是類型列表。
如果您希望“列”成為字典,請嘗試這樣的操作。
列 = {'city_indiv':'city_name','post_id_indiv':'post_id','content_indiv':'content_of_indiv','content_media':'content_of_media'}。
然后您可以對列執行鍵值操作,因為它是 dict 類型。
使用df_userpolice.groupby("event_id").size()
獲取每個event_id
的行數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.