[英]Adding series to Pandas dataframe yields column of NaN
使用此數據集(為簡潔起見,省略了一些cols和數百行)。 。 。
Year Ceremony Award Winner Name
0 1927/1928 1 Best Actress 0.0 Louise Dresser
1 1927/1928 1 Best Actress 1.0 Janet Gaynor
2 1937 10 Best Actress 0.0 Janet Gaynor
3 1927/1928 1 Best Actress 0.0 Gloria Swanson
4 1929/1930 3 Best Actress 0.0 Gloria Swanson
5 1950 23 Best Actress 0.0 Gloria Swanson
我使用了以下命令。 。 。
ba_dob.loc[ba_dob.Winner == 0.0, :].groupby('Name').Winner.count()
要創建以下系列。 。 。
Name
Ali MacGraw 1
Amy Adams 1
Angela Bassett 1
Angelina Jolie 1
Anjelica Huston 1
Ann Harding 1
Ann-Margret 1
Anna Magnani 1
Anne Bancroft 4
Anne Baxter 1
Anne Hathaway 1
Annette Bening 3
Audrey Hepburn 4
我嘗試將系列添加到原始數據框中,就像這樣。 。 。
ba_dob['New_Col'] = ba_dob.loc[ba_dob.Winner == 0.0, :].groupby('Name').Winner.count()
我得到了一列NaN值。
我已經閱讀了其他帖子,表明工作中可能存在一些錯誤的索引,但我不確定這會如何發生。 更具體地說,為什么Pandas無法排列索引,因為groupby和count來自同一個表。 還有其他事情在發生嗎?
我認為你需要size
,而不是count
,因為count
排除NaN
:
上一個map
列按groupby
創建的Series
Name
:
m = ba_dob.Winner == 0.0
ba_dob['new'] = ba_dob['Name'].map(ba_dob[m].groupby('Name').Winner.size())
print (ba_dob)
Year Ceremony Award Winner Name new
0 1927/1928 1 Best Actress 0.0 Louise Dresser 1
1 1927/1928 1 Best Actress 1.0 Janet Gaynor 1
2 1937 10 Best Actress 0.0 Janet Gaynor 1
3 1927/1928 1 Best Actress 0.0 Gloria Swanson 3
4 1929/1930 3 Best Actress 0.0 Gloria Swanson 3
5 1950 23 Best Actress 0.0 Gloria Swanson 3
另一種方案:
ba_dob['new'] = ba_dob['Name'].map(ba_dob.loc[m, 'Name'].value_counts())
您可以在初始數據框中加入結果
New_col = df.loc[df.Winner == 0.0, :].groupby('Name').Winner.count().rename('New_col')
df = df.join(New_col, on='Name')
輸出:
Award Ceremony Name Winner Year New_col
0 Best Actress 1927/1928 Louise Dresser 0.0 0 1
1 Best Actress 1927/1928 Janet Gaynor 1.0 1 1
2 Best Actress 1937 Janet Gaynor 0.0 2 1
3 Best Actress 1927/1928 Gloria Swanson 0.0 3 3
4 Best Actress 1929/1930 Gloria Swanson 0.0 4 3
5 Best Actress 1950 Gloria Swanson 0.0 5 3
你也可以使用地圖
mapper = ba_dob.loc[ba_dob.Winner == 0.0, :].groupby('Name').Winner.count()
ba_dob['New_Col'] = ba_dob['Name'].map(mapper)
你得到
Year Ceremony Award Winner Name New_Col
0 1927/1928 1 BestActress 0.0 Louise Dresser 1
1 1927/1928 1 BestActress 1.0 Janet Gaynor 1
2 1937 10 BestActress 0.0 Janet Gaynor 1
3 1927/1928 1 BestActress 0.0 Gloria Swanson 3
4 1929/1930 3 BestActress 0.0 Gloria Swanson 3
5 1950 23 BestActress 0.0 Gloria Swanson 3
您需要使用reset_index(),它會刪除層次結構並創建兩個字段Name&Count.Post,選擇“Count”字段將其添加到dataframe。 就像是
ba_dob['New_Col'] = ba_dob.loc[ba_dob.Winner == 0.0, :].groupby('Name').Winner.count().reset_index()['count']
您的groupby
不會覆蓋整個DataFrame
,只會覆蓋Winner == 0
的行,所以當然對於這些行,您將獲得NaN
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.