相关疑难解决方法(0)

如何在Pandas中处理SettingWithCopyWarning?

背景

我刚刚将我的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)

python dataframe pandas chained-assignment

536
推荐指数
16
解决办法
58万
查看次数

将字符串转换为DataFrame中的浮点数

如何将包含字符串和NaN值的DataFrame列转换为浮点数.还有另一列,其值为字符串和浮点数; 如何将整个列转换为浮点数.

python pandas

103
推荐指数
5
解决办法
27万
查看次数

Python Pandas - 将一些列类型更改为类别

我已将以下CSV文件输入iPython Notebook:

public = pd.read_csv("categories.csv")
public
Run Code Online (Sandbox Code Playgroud)

我还将pandas导入为pd,将numpy导入为np,将matplotlib.pyplot导入为plt.存在以下数据类型(以下是摘要 - 大约有100列)

In [36]:   public.dtypes
Out[37]:   parks          object
           playgrounds    object
           sports         object
           roading        object               
           resident       int64
           children       int64
Run Code Online (Sandbox Code Playgroud)

我希望将"公园","游乐场","体育"和"漫游"更改为类别(他们在其中有类似的比例反应 - 每列都有不同类型的喜欢的回应(例如,一个人"非常同意","同意"等等,另一个具有"非常重要","重要"等等,其余部分为int64.

我能够创建一个单独的数据框 - public1 - 并使用以下代码将其中一列更改为类别类型:

public1 = {'parks': public.parks}
public1 = public1['parks'].astype('category')
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用此代码一次更改数字时,我没有成功:

public1 = {'parks': public.parks,
           'playgrounds': public.parks}
public1 = public1['parks', 'playgrounds'].astype('category')
Run Code Online (Sandbox Code Playgroud)

尽管如此,我不想仅使用类别列创建单独的数据框.我想在原始数据框中更改它们.

我尝试了很多方法来实现这一点,然后在这里尝试了代码:Pandas:更改列的数据类型 ...

public[['parks', 'playgrounds', 'sports', 'roading']] = public[['parks', 'playgrounds', 'sports', 'roading']].astype('category')
Run Code Online (Sandbox Code Playgroud)

并得到以下错误:

 NotImplementedError: > 1 ndim Categorical are not supported at this time
Run Code Online (Sandbox Code Playgroud)

有没有办法改变"公园","游乐场","体育","漫步"到类别(这样可以分析比特率的反应),留下"常驻"和"儿童"(以及94个其他列是字符串,int +浮动)请原谅?或者,有更好的方法吗?如果有人有任何建议和/或反馈我会非常感激....我慢慢地去秃头撕开我的头发!

提前谢谢了.

编辑添加 …

python numpy multiple-columns categories pandas

42
推荐指数
5
解决办法
5万
查看次数

将整个pandas数据帧转换为pandas中的整数(0.17.0)

我的问题与非常相似,但我需要转换整个数据帧而不仅仅是一系列.该to_numeric函数一次只能在一个系列上运行,并且不能替代已弃用的convert_objects命令.有没有办法convert_objects(convert_numeric=True)在新的pandas版本中获得与命令类似的结果?

谢谢MikeMüller的例子.df.apply(pd.to_numeric)如果值都可以转换为整数,则效果很好.如果在我的数据框中我有无法转换为整数的字符串怎么办?例:

df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']})
df.dtypes
Out[59]: 
Words    object
ints     object
dtype: object
Run Code Online (Sandbox Code Playgroud)

然后我可以运行已弃用的函数并获取:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[60]: 
Words    object
ints      int64
dtype: object
Run Code Online (Sandbox Code Playgroud)

运行该apply命令会给我带来错误,即使是尝试和处理也是如此.

python pandas

33
推荐指数
2
解决办法
5万
查看次数

嵌套Json到pandas DataFrame具有特定格式

我需要在pandas DataFrame中以特定格式格式化Json文件的内容,以便我可以运行pandassql来转换数据并通过评分模型运行它.

file = C:\ scoring_model\json.js('file'的内容如下)

{
"response":{
  "version":"1.1",
  "token":"dsfgf",
   "body":{
     "customer":{
         "customer_id":"1234567",
         "verified":"true"
       },
     "contact":{
         "email":"mr@abc.com",
         "mobile_number":"0123456789"
      },
     "personal":{
         "gender": "m",
         "title":"Dr.",
         "last_name":"Muster",
         "first_name":"Max",
         "family_status":"single",
         "dob":"1985-12-23",
     }
   }
 }
Run Code Online (Sandbox Code Playgroud)

我需要数据框看起来像这样(显然在同一行上的所有值,尝试尽可能地格式化这个问题):

version | token | customer_id | verified | email      | mobile_number | gender |
1.1     | dsfgf | 1234567     | true     | mr@abc.com | 0123456789    | m      |

title | last_name | first_name |family_status | dob
Dr.   | Muster    | Max        | single       | 23.12.1985
Run Code Online (Sandbox Code Playgroud)

我已经查看了有关此主题的所有其他问题,尝试了各种方法将Json文件加载到pandas中

`with open(r'C:\scoring_model\json.js', 'r') …
Run Code Online (Sandbox Code Playgroud)

python format json nested pandas

31
推荐指数
1
解决办法
3万
查看次数

何时申请(pd.to_numeric)以及何时在python中使用astype(np.float64)?

我有一个名为pandas的DataFrame对象xiv,它有一列int64Volume测量值.

In[]: xiv['Volume'].head(5)
Out[]: 

0    252000
1    484000
2     62000
3    168000
4    232000
Name: Volume, dtype: int64
Run Code Online (Sandbox Code Playgroud)

我已经阅读了其他帖子(比如这个这个),提出了以下解决方案.但是,当我使用任何一种方法时,它似乎不会改变dtype底层数据:

In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume'])

In[]: xiv['Volume'].dtypes
Out[]: 
dtype('int64')
Run Code Online (Sandbox Code Playgroud)

要么...

In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume'])
Out[]: ###omitted for brevity###

In[]: xiv['Volume'].dtypes
Out[]: 
dtype('int64')

In[]: xiv['Volume'] = xiv['Volume'].apply(pd.to_numeric)

In[]: xiv['Volume'].dtypes
Out[]: 
dtype('int64')
Run Code Online (Sandbox Code Playgroud)

我也尝试制作一个单独的pandas Series并使用上面列出的方法在该系列上并重新分配给x['Volume']obect,这是一个pandas.core.series.Series对象.

但是,我已经使用numpy包的float64类型找到了解决这个问题的方法- 这有效,但我不知道它为什么会有所不同.

In[]: xiv['Volume'] = xiv['Volume'].astype(np.float64)

In[]: xiv['Volume'].dtypes
Out[]: 
dtype('float64') …
Run Code Online (Sandbox Code Playgroud)

python types numpy dataframe pandas

30
推荐指数
1
解决办法
4万
查看次数

将pypeas.Series从dtype对象转换为float,将错误转换为nans

考虑以下情况:

In [2]: a = pd.Series([1,2,3,4,'.'])

In [3]: a
Out[3]: 
0    1
1    2
2    3
3    4
4    .
dtype: object

In [8]: a.astype('float64', raise_on_error = False)
Out[8]: 
0    1
1    2
2    3
3    4
4    .
dtype: object
Run Code Online (Sandbox Code Playgroud)

我本来期望一个允许转换的选项,同时将错误的值(例如那个.)转换为NaNs.有没有办法实现这个目标?

python pandas

24
推荐指数
2
解决办法
9万
查看次数

如何更改pandas中多列的数据类型

我正在尝试在 pandas 数据帧上运行随机森林。我知道数据框中没有空值或无穷大,但当我拟合模型时不断收到 ValueError 。大概这是因为我有 flaot64 列而不是 float32;我还有很多 bool 和 int 类型的列。有没有办法将所有 float 列更改为 float32?

我尝试重写 CSV,并且相对确定问题不在于此。我以前从未在 float64 上运行随机森林时遇到过问题,所以我不确定这次出了什么问题。

labels = electric['electric_ratio']
electric = electric[[x for x in electric.columns if x != 'electric_ratio']]
electric_list = electric.columns
first_train, first_test, train_labels, test_labels = train_test_split(electric, labels)
rf = RandomForestRegressor(n_estimators = 1000, random_state=88)
rf_1 = rf.fit(first_train, train_labels)
Run Code Online (Sandbox Code Playgroud)

我希望这适合模型,但始终得到

ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
Run Code Online (Sandbox Code Playgroud)

python machine-learning pandas random-forest jupyter-notebook

24
推荐指数
3
解决办法
3万
查看次数

Pandas infer_objects() 不会将字符串列转换为数字

我有一个数据源,其中所有值都以字符串形式给出。当我从这些数据创建 Pandas 数据框时,所有列自然都是类型object。然后我想让 Pandas自动将任何看起来像数字的列转换为数字类型(例如int64, float64)。

据推测,Pandas 提供了一个函数来执行这种自动类型推断:pandas.DataFrame.infer_objects()StackOverflow 帖子中也提到了这一点。文档说:

尝试对对象数据类型列进行软转换,使非对象列和不可转换列保持不变。推理规则与正常的 Series/DataFrame 构造期间相同。

但是,该功能对我不起作用。在下面的可重现示例中,我有两个字符串列(value1value2),它们分别明确地类似于intfloat值,但infer_objects()不会将它们从字符串转换为适当的数字类型。

import pandas as pd

# Create example dataframe.
data = [ ['Alice', '100', '1.1'], ['Bob', '200', '2.1'], ['Carl', '300', '3.1']]
df = pd.DataFrame(data, columns=['name', 'value1', 'value2'])

print(df)

#     name value1 value2
# 0  Alice    100    1.1
# 1    Bob    200    2.1
# 2   Carl    300    3.1

print(df.info()) …
Run Code Online (Sandbox Code Playgroud)

python pandas

12
推荐指数
1
解决办法
5983
查看次数

获取TypeError:尝试使用idxmax()时,此dtype不允许使用还原操作'argmax'

idxmax()在Pandas中使用该功能时,我一直收到此错误.

Traceback (most recent call last):
  File "/Users/username/College/year-4/fyp-credit-card-fraud/code/main.py", line 20, in <module>
    best_c_param = classify.print_kfold_scores(X_training_undersampled, y_training_undersampled)
  File "/Users/username/College/year-4/fyp-credit-card-fraud/code/Classification.py", line 39, in print_kfold_scores
    best_c_param = results.loc[results['Mean recall score'].idxmax()]['C_parameter']
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/series.py", line 1369, in idxmax
    i = nanops.nanargmax(_values_from_object(self), skipna=skipna)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/nanops.py", line 74, in _f
    raise TypeError(msg.format(name=f.__name__.replace('nan', '')))
TypeError: reduction operation 'argmax' not allowed for this dtype
Run Code Online (Sandbox Code Playgroud)

我正在使用的熊猫版本是 0.22.0

main.py

import ExploratoryDataAnalysis as eda
import Preprocessing as processor
import Classification as classify
import pandas as pd


data_path = '/Users/username/college/year-4/fyp-credit-card-fraud/data/'

if __name__ …
Run Code Online (Sandbox Code Playgroud)

python python-3.x pandas

11
推荐指数
2
解决办法
9044
查看次数