我刚刚将我的Pandas从0.11升级到0.13.0rc1.现在,该应用程序正在弹出许多新的警告.其中一个是这样的:
E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
Run Code Online (Sandbox Code Playgroud)
我想知道究竟是什么意思?我需要改变什么吗?
如果我坚持使用,我应该如何暂停警告quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE?
def _decode_stock_quote(list_of_150_stk_str):
"""decode the webpage and return dataframe"""
from cStringIO import StringIO
str_of_all = "".join(list_of_150_stk_str)
quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
quote_df['TClose'] = quote_df['TPrice']
quote_df['RT'] …Run Code Online (Sandbox Code Playgroud) 我一直在探索如何优化我的代码并运行pandas .at方法.根据文档
基于标签的快速标量访问器
与loc类似,at提供基于标签的标量查找.您也可以使用这些索引器进行设置.
所以我跑了一些样品:
import pandas as pd
import numpy as np
from string import letters, lowercase, uppercase
lt = list(letters)
lc = list(lowercase)
uc = list(uppercase)
def gdf(rows, cols, seed=None):
"""rows and cols are what you'd pass
to pd.MultiIndex.from_product()"""
gmi = pd.MultiIndex.from_product
df = pd.DataFrame(index=gmi(rows), columns=gmi(cols))
np.random.seed(seed)
df.iloc[:, :] = np.random.rand(*df.shape)
return df
seed = [3, 1415]
df = gdf([lc, uc], [lc, uc], seed)
print df.head().T.head().T
Run Code Online (Sandbox Code Playgroud)
df 好像:
a
A B C D E …Run Code Online (Sandbox Code Playgroud) 对于这个问题,这是一个相当类似的问题,但有一个关键的区别:我选择的数据不是通过索引而是通过某些标准来改变.
如果我应用的条件返回单行,我希望能够以一种简单的方式设置该行中某列的值,但我的第一次尝试不起作用:
>>> d = pd.DataFrame({'year':[2008,2008,2008,2008,2009,2009,2009,2009],
... 'flavour':['strawberry','strawberry','banana','banana',
... 'strawberry','strawberry','banana','banana'],
... 'day':['sat','sun','sat','sun','sat','sun','sat','sun'],
... 'sales':[10,12,22,23,11,13,23,24]})
>>> d
day flavour sales year
0 sat strawberry 10 2008
1 sun strawberry 12 2008
2 sat banana 22 2008
3 sun banana 23 2008
4 sat strawberry 11 2009
5 sun strawberry 13 2009
6 sat banana 23 2009
7 sun banana 24 2009
>>> d[d.sales==24]
day flavour sales year
7 sun banana 24 2009
>>> d[d.sales==24].sales = 100
>>> d
day …Run Code Online (Sandbox Code Playgroud) 我有一个227x4 DataFrame,国家名称和数值要清理(争吵?).
这是DataFrame的抽象:
import pandas as pd
import random
import string
import numpy as np
pdn = pd.DataFrame(["".join([random.choice(string.ascii_letters) for i in range(3)]) for j in range (6)], columns =['Country Name'])
measures = pd.DataFrame(np.random.random_integers(10,size=(6,2)), columns=['Measure1','Measure2'])
df = pdn.merge(measures, how= 'inner', left_index=True, right_index =True)
df.iloc[4,1] = 'str'
df.iloc[1,2] = 'stuff'
print(df)
Country Name Measure1 Measure2
0 tua 6 3
1 MDK 3 stuff
2 RJU 7 2
3 WyB 7 8
4 Nnr str 3
5 rVN 7 4
Run Code Online (Sandbox Code Playgroud)
如何np.nan在不触及国家/地区名称的情况下在所有列中替换字符串值? …
我收到警告“
C:\Python27\lib\site-packages\pandas\core\indexing.py:411: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s"
Run Code Online (Sandbox Code Playgroud)
虽然按照文档中的建议,我正在使用 df.loc ?
def sentenceInReview(df):
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
print "size of df: " + str(df.size)
df.loc[: ,'review_text'] = df.review_text.map(lambda x: tokenizer.tokenize(x))
print df[:3]
Run Code Online (Sandbox Code Playgroud) 假设我想要一个函数来更改DataFrame的给定行号中的命名列的值.
一种选择是找到列的位置并使用iloc,如下所示:
def ChangeValue(df, rowNumber, fieldName, newValue):
columnNumber = df.columns.get_loc(fieldName)
df.iloc[rowNumber, columnNumber] = newValue
Run Code Online (Sandbox Code Playgroud)
但是我想知道是否有办法一次性使用iloc和loc的魔法,并跳过手动转换.
有任何想法吗?
就在我认为自己已经掌握了Python和Pandas的时候,另一个看似简单的问题就出现了.我想将元组添加到pandas数据帧的特定单元格中.这些元组需要根据数据帧中其他单元格的内容即时计算 - 换句话说,我不能提前计算所有元组并将它们添加为单个数组.
举个例子,我用一些数据定义一个数据帧并添加几个空列:
import pandas as pd
import bumpy as np
tempDF = pd.DataFrame({'miscdata': [1.2,3.2,4.1,2.3,3.3,2.5,4.3,2.5,2.2,4.2]})
tempDF['newValue'] = np.nan
tempDF['newTuple'] = np.nan
Run Code Online (Sandbox Code Playgroud)
我可以滚动浏览'newValue'列的每个单元格并添加一个没有问题的整数值:
anyOldValue = 3.5
for i in range(10):
tempDF.ix[(i,'newValue')] = anyOldValue
print tempDF
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试添加元组,我会收到一条错误消息:
anyOldTuple = (2.3,4.5)
for i in range(10):
tempDF.ix[(i,'newTuple')] = anyOldTuple
print tempDF
Run Code Online (Sandbox Code Playgroud)
我收到了几条错误消息,包括:
ValueError: Must have equal len keys and value when setting with an ndarray
Run Code Online (Sandbox Code Playgroud)
…和…
ValueError: setting an array element with a sequence.
Run Code Online (Sandbox Code Playgroud)
我确定我已经在单元格中看到了带有元组(或列表)的数据框 - 不是吗?任何有关如何使此代码工作的建议将非常感激.
我在Python Pandas数据帧上有两个与索引相关的问题.
import pandas as pd
import numpy as np
df = pd.DataFrame({'id' : range(1,9),
'B' : ['one', 'one', 'two', 'three',
'two', 'three', 'one', 'two'],
'amount' : np.random.randn(8)})
df = df.ix[df.B != 'three'] # remove where B = three
df.index
>> Int64Index([0, 1, 2, 4, 6, 7], dtype=int64) # the original index is preserved.
Run Code Online (Sandbox Code Playgroud)
1)我不明白为什么修改数据帧后索引不会自动更新.有没有办法在修改数据帧时自动更新索引?如果没有,那么最有效的手动方式是什么?
2)我希望能够B将第5个元素的列设置df为"3".但df.iloc[5]['B'] = 'three'不这样做.我查看了手册,但没有介绍如何更改按位置访问的特定单元格值.
如果我按行名访问,我可以这样做:df.loc[5,'B'] = 'three'但我不知道索引访问等价物是什么.
我正在尝试替换数据框中的某些数据以包含额外的“F”。
代码应如下所示:
if testdata['pfType'] =='NK225M'|testdata['pfType'] == 'TOPIXM':
testdata['pfType'] = ' testdata['pfType'] & 'F';
Run Code Online (Sandbox Code Playgroud)
我试图这样做:
testdata['pfType'][testdata['pfType'] == 'NK225M'] = 'NK225MF'
testdata['pfType'][testdata['pfType'] == 'TOPIXM'] = 'TOPIXMF'
Run Code Online (Sandbox Code Playgroud)
但它并没有改变这些值,如果它是 NK225M 或 TOPIXM,那么将“F”添加到字符串的最佳方法是什么。