我正在嘗試對.count()“pos”和“neg”這個詞出現的次數做一個簡單的操作,以便我可以將它應用到 Seaborn 上的條形圖的 Y 軸上。
這是我的代碼:
df['score'] = df['compound'].apply(lambda x: 'pos' if x>= 0 else 'neg')
df['overall'] = df[(df.score == "pos") & (df.score == "neg")].count()
plt.figure(2)
chart_2 = sns.barplot(x='Category', y='overall', data=df)
當我運行它時, plt.figure(2) 回傳一個空圖表。我試過.sum()哪個不起作用并且還回傳一個空圖表。
如果我執行此操作,它將回傳總體總數,而不會Category在 x-ais 中對其進行分解。例如,所有類別總共有 58 個,這是資料框的總數。
df['overall'] = df['score'].count()
.value_counts()還回傳一個空圖表。
對于為什么會出現這種情況,我已經沒有想法了!
提前致謝。
uj5u.com熱心網友回復:
如評論中所述,(df.score == "pos") & (df.score == "neg")通過AND關系組合并False在所有情況下都會給出。在所有情況下,使用ORas in(df.score == "pos") | (df.score == "neg")都會給出 True。但是,它不會區分類別,所以df['overall']到處都是 58。
創建計數條形圖的最簡單方法是 seaborn 的sns.countplot(). 您可以設定x='Category'對每個類別進行計數。hue='score'將通過分數分裂。
要直接創建條形圖并通過 pandas 進行計數,您需要類似df['overall'] = df['Category'].apply(lambda cat: (df['Category'] == cat).sum()). 在這里,創建一個布林值和值(df['Category'] == cat)陣列。當被呼叫到這些時,被認為是,所以將計算值的數量。TrueFalsesum()True1False0sum()True
Pandas 首選的按類別計數的方法是通過groupby('Category'),然后從size()每個組中獲取。
這是一個例子:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.DataFrame({'compound': [-20, -10, 100, 200, 300, -20, -10, 100, -10, 100, 200, 300],
'Category': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c']})
df['score'] = df['compound'].apply(lambda x: 'pos' if x >= 0 else 'neg')
fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4, figsize=(14, 4))
sns.countplot(data=df, x='Category', hue='score', palette='rocket', ax=ax1)
ax1.set_title('Countplot: Score per category')
ax1.locator_params(axis='y', integer=True)
sns.countplot(data=df, x='Category', palette='turbo', ax=ax2)
ax2.set_title('Countplot: Overall sum per category')
df['overall'] = df['Category'].apply(lambda cat: (df['Category'] == cat).sum())
sns.barplot(data=df, x='Category', y='overall', palette='turbo', ax=ax3)
ax3.set_title('Barplot: Using the "overall" column')
df_counts = df.groupby('Category', as_index=False).size()
sns.barplot(data=df_counts, x='Category', y='size', palette='turbo', ax=ax4)
ax4.set_title('Barplot: Using groupby')
sns.despine()
plt.tight_layout()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414227.html
標籤:
