尝试使用以下格式将csv文件读入pandas数据帧
dp = pd.read_csv('products.csv', header = 0, dtype = {'name': str,'review': str,
'rating': int,'word_count': dict}, engine = 'c')
print dp.shape
for col in dp.columns:
print 'column', col,':', type(col[0])
print type(dp['rating'][0])
dp.head(3)
Run Code Online (Sandbox Code Playgroud)
这是输出:
(183531, 4)
column name : <type 'str'>
column review : <type 'str'>
column rating : <type 'str'>
column word_count : <type 'str'>
<type 'numpy.int64'>
Run Code Online (Sandbox Code Playgroud)
我可以理解,大熊猫可能会发现很难将字典的字符串表示转换为字典并给出这个和这个.但是如何将"rating"列的内容同时为str和numpy.int64 ???
顺便说一下,不指定引擎或标题的调整不会改变任何东西.
感谢致敬
我有两个大型Dataframe合并的问题,因为虽然有合适的值,但合并返回NaN值.这两个dfs的形状如下:
DF1
Motor
2232
1524
2230
2230
2224
1516
1724
2224
1524
1624
1724
2224
2224
1524
1524
1516
1524
2224
1624
1724
1724
2224
2224
Run Code Online (Sandbox Code Playgroud)
DF2
Motor Output Torque (mNm)
0615 0,17
1219 0,72
1516 0,59
1624 2
2230 4,7
2233 5,9
0816 0,7
1016 0,92
1024 1,6
1224 1,7
1319 1,4
1331 3,8
1516 0,97
1524 2,9
1717 2,2
1724 4,5
2224 6,8
2232 10
1336 3,6
1727 4,9
1741 8,8
2237 12
2642 26
Run Code Online (Sandbox Code Playgroud)
我用的代码是:
MergeDat=MergeDat.merge(Motor,how="left")
print(MergeDat) …Run Code Online (Sandbox Code Playgroud) 我想更改一个数据框列的dtype(从datetime64到object).
首先,我创建数据框:
Python 2.6.8 (unknown, Jan 26 2013, 14:35:25)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> values = pd.Series(i for i in range(5))
>>> dates = pd.date_range('20130101',periods=5)
>>> df = pd.DataFrame({'values': values, 'dates': dates})
>>> df
/usr/local/lib/python2.6/dist-packages/pandas/core/config.py:570: DeprecationWarning: height has been deprecated.
warnings.warn(d.msg, DeprecationWarning)
dates values
0 2013-01-01 00:00:00 0
1 2013-01-02 00:00:00 1
2 2013-01-03 00:00:00 2
3 2013-01-04 00:00:00 3
4 2013-01-05 00:00:00 4
Run Code Online (Sandbox Code Playgroud)
它有两列:一列是datetime64,另一列是int64 dtype: …
假设我想要一个函数来更改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的魔法,并跳过手动转换.
有任何想法吗?
我正在使用 AlphaVantage API 下载数据点,然后将其转换为 pandas DataFrame。
我想使用 Plotly 用散点图/折线图绘制新的 DataFrame。在 Google Colab 中绘制这些图表时,这些图表似乎很完美,但是,我似乎无法在 PyCharm 和 Jupiter Notebook 中复制我的结果。
在 PyCharm 和 JN 中绘图时,Y 轴值绘制无序,就像图表试图创建尽可能直线一样(参见第二张图片并仔细观察 y 轴)。
这是代码和图表的简化示例:
两个实例中使用完全相同的代码
参见代码:
import requests
import pandas as pd
import plotly.graph_objects as go
# DATA FROM API
response = requests.get(url='https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=IBM&apikey=demo')
response.raise_for_status()
stock_weekly = response.json()['Weekly Time Series']
# CHANGE DATA FORMAT, RENAME COLUMNS AND CONVERT TO DATETIME, FINALLY FLIP TO HAVE DATE IN ASCENDING ORDER
raw_weekly_data = pd.DataFrame(stock_weekly) …Run Code Online (Sandbox Code Playgroud) 我实际上不知道我的代码有什么问题。有人可以帮忙吗?
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold, cross_val_score
from sklearn.metrics import confusion_matrix,precision_recall_curve,auc,roc_auc_score,roc_curve,recall_score,classification_report
def printing_Kfold_scores(x_train_data,y_train_data):
fold = KFold(len(y_train_data),5,shuffle=False)
# Different C parameters
c_param_range = [0.01,0.1,1,10,100]
results_table = pd.DataFrame(index = range(len(c_param_range),2), columns = ['C_parameter','Mean recall score'])
results_table['C_parameter'] = c_param_range
# the k-fold will give 2 lists: train_indices = indices[0], test_indices = indices[1]
j = 0
for c_param in c_param_range:
print('-------------------------------------------')
print('C parameter: ', c_param)
print('-------------------------------------------')
print('')
recall_accs = []
for iteration, indices in enumerate(fold,start=1):
# Call the logistic regression model …Run Code Online (Sandbox Code Playgroud) 我按照这里的建议更改了pandas数据帧的列数据类型.但是,如果我按索引号而不是列名引用列,它似乎不起作用.有没有办法正确地做到这一点?
In [49]: df.iloc[:, 4:].astype(int)
Out[49]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5074 entries, 0 to 5073
Data columns (total 3 columns):
5 5074 non-null values
6 5074 non-null values
7 5074 non-null values
dtypes: int64(3)
In [50]: df.iloc[:, 4:] = df.iloc[:, 4:].astype(int)
In [51]: df
Out[51]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5074 entries, 0 to 5073
Data columns (total 7 columns):
1 5074 non-null values
2 5074 non-null values
3 5074 non-null values
4 5074 non-null values
5 5074 non-null values
6 …Run Code Online (Sandbox Code Playgroud) 我有各种csv文件,我将它们导入为DataFrame.问题是许多文件使用不同的符号来表示缺失值.有些人使用nan,其他人使用NaN,ND,无,丢失等等,或只是将条目空白.有没有办法用np.nan替换所有这些值?换句话说,数据框中的任何非数字值都将变为np.nan.感谢您的帮助.
我从csv文件中读取了一些天气数据作为名为"weather"的数据帧.问题是列的数据类型之一是一个对象.这是奇怪的,因为它表示温度......无论如何,如何将其更改为浮点数?我试过to_numeric但它无法解析它.
weather.info()
weather.head()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 304 entries, 2017-01-01 to 2017-10-31
Data columns (total 2 columns):
Temp 304 non-null object
Rain 304 non-null float64
dtypes: float64(1), object(1)
memory usage: 17.1+ KB
Temp Rain
Date
2017-01-01 12.4 0.0
2017-02-01 11 0.6
2017-03-01 10.4 0.6
2017-04-01 10.9 0.2
2017-05-01 13.2 0.0
Run Code Online (Sandbox Code Playgroud) 我想将我的数据帧的所有非浮点类型列转换为浮点数,有什么方法可以做到.如果我可以在One Go中执行它,那将会很棒.以下是类型
longitude - float64
latitude - float64
housing_median_age - float64
total_rooms - float64
total_bedrooms - object
population - float64
households - float64
median_income - float64
rooms_per_household - float64
category_<1H OCEAN - uint8
category_INLAND - uint8
category_ISLAND - uint8
category_NEAR BAY - uint8
category_NEAR OCEAN - uint8
Run Code Online (Sandbox Code Playgroud)
import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
df = pd.DataFrame(housing)
df['ocean_proximity'] = pd.Categorical(df['ocean_proximity']) #type casting
dfDummies = pd.get_dummies(df['ocean_proximity'], prefix = 'category' )
df = pd.concat([df, dfDummies], axis=1) …Run Code Online (Sandbox Code Playgroud)