我有一個DataFrame(df_test)帶有可以按行標籤分組的行標籤('字母')和列名('數字')。設置多索引熊貓DataFrame的特定單元格
>>> letters = ['a','a','a','a','a','b','b','b','c','c','c','c']
>>> n = {'numbers': [0,1,2,3,4,0,1,2,0,1,2,3]}
>>> df_test = pd.DataFrame(n, index=letters)
>>> print df_test
numbers
a 0
a 1
a 2
a 3
a 4
b 0
b 1
b 2
c 0
c 1
c 2
c 3
我想創建一個名爲'位置'的新列。每組的第一行(即組a,組b,組c)應該是'S',最後一行應該是'E',並且中間行應該是'M'。 (對於開始,中間和結尾;))它是這樣的:
numbers Position
a 0 S
a 1 M
a 2 M
a 3 M
a 4 E
b 0 S
b 1 M
b 2 E
c 0 S
c 1 M
c 2 M
c 3 E
我一直在使用的.loc和.iloc的組合,我的新的價值分配到正確的細胞,但得到的嘗試錯誤信息。
>>> df_test['Position'] = 'M'
>>> for idxName,frame in df_test.groupby(level=0):
df_test.loc[idxName,('Position')].iloc[0] = 'S'
df_test.loc[idxName,('Position')].iloc[-1] = 'E'
__main__:2: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
__main__:3: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
我想,這個問題試圖使用.iloc []有使用的.loc []後出現,但我不知道熊貓足夠好,有不同的解決方案,並沒有發現任何東西,儘管在線小時的搜索。 (a)瞭解爲什麼我會收到警告和(b)將我的單元格設置爲正確值的任何幫助將非常感謝!
謝謝 - 這對我的模擬DataFrame完美的作品。不幸的是,當我嘗試將它應用到我的實際DataFrame(基本上是相同的結構,但有更多列)時,我得到以下錯誤消息:''不能從重複的軸重新索引。「'你知道爲什麼這可能是發生了什麼? (df_test有一個從a到c和2列有12個條目的索引;我的其他df有一個索引,從B01_H01到B03_H03和31列有25個條目。) – YerABlizzardHarry
@YerABlizzardHarry我更新了答案 – piRSquared
我也想過擺脫'concat'行會有所作爲,但我仍然遇到同樣的錯誤。我的DataFrame一定有問題。如果可能的話,我會玩弄它併發佈一個新問題。感謝你的幫助! – YerABlizzardHarry