GVKun编程网logo

在pandas中创建多个移位(滞后)列(pandas 移动列的位置)

12

本文将带您了解关于在pandas中创建多个移位的新内容,同时我们还将为您解释滞后列的相关知识,另外,我们还将为您提供关于database–在PostgreSQL表中创建多个索引的缺点、database

本文将带您了解关于在pandas中创建多个移位的新内容,同时我们还将为您解释滞后列的相关知识,另外,我们还将为您提供关于database – 在PostgreSQL表中创建多个索引的缺点、database – 如何在一个表中创建多个序列?、Groupby 移位(滞后值)模拟,只有 Numpy(无熊猫) 对虚拟数据进行测试 -、Pandas无法读取在PySpark中创建的实木复合地板文件的实用信息。

本文目录一览:

在pandas中创建多个移位(滞后)列(pandas 移动列的位置)

在pandas中创建多个移位(滞后)列(pandas 移动列的位置)

我有一个时序DataFrame,我想复制我的200个功能/列中的每一个作为其他滞后功能。因此,目前我在时间t处具有要素,并希望在时间步t-1,t-2等处创建要素。

我知道最好用df.shift()来完成,但是我很难将其完全合并。我还想将列重命名为“功能(t-1)”,“功能(t-2)”。

我的伪代码尝试将是这样的:

lagged_values = [1,2,3,10]for every lagged_values    for every column, make a new feature column with df.shift(lagged_values)    make new column have name ''original col name''+''(t-(lagged_values))''

最后,如果我有200列和4个滞后时间步长,那么我将拥有一个具有1000个特征的新df(在t,t-1,t-2,t-3和t-10处各有200个)。

我发现类似的东西,但是按照机器学习的掌握,它不会保留原始的列名(重命名为var1,var2等)。不幸的是,我对它的理解不足以将其修改为我的问题。

def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):    """    Frame a time series as a supervised learning dataset.    Arguments:        data: Sequence of observations as a list or NumPy array.        n_in: Number of lag observations as input (X).        n_out: Number of observations as output (y).        dropnan: Boolean whether or not to drop rows with NaN values.    Returns:        Pandas DataFrame of series framed for supervised learning.    """    n_vars = 1 if type(data) is list else data.shape[1]    df = DataFrame(data)    cols, names = list(), list()    # input sequence (t-n, ... t-1)    for i in range(n_in, 0, -1):        cols.append(df.shift(i))        names += [(''var%d(t-%d)'' % (j+1, i)) for j in range(n_vars)]    # forecast sequence (t, t+1, ... t+n)    for i in range(0, n_out):        cols.append(df.shift(-i))        if i == 0:            names += [(''var%d(t)'' % (j+1)) for j in range(n_vars)]        else:            names += [(''var%d(t+%d)'' % (j+1, i)) for j in range(n_vars)]    # put it all together    agg = concat(cols, axis=1)    agg.columns = names    # drop rows with NaN values    if dropnan:        agg.dropna(inplace=True)    return agg

答案1

小编典典

您可以使用字典理解功能创建其他列,然后通过将它们添加到数据框中assign

df = pd.DataFrame(np.random.randn(5, 2), columns=list(''AB''))lags = range(1, 3)  # Just two lags for demonstration.>>> df.assign(**{    ''{} (t-{})''.format(col, t): df[col].shift(t)    for t in lags    for col in df})          A         B   A (t-1)   A (t-2)   B (t-1)   B (t-2)0 -0.773571  1.945746       NaN       NaN       NaN       NaN1  1.375648  0.058043 -0.773571       NaN  1.945746       NaN2  0.727642  1.802386  1.375648 -0.773571  0.058043  1.9457463 -2.427135 -0.780636  0.727642  1.375648  1.802386  0.0580434  1.542809 -0.620816 -2.427135  0.727642 -0.780636  1.802386

database – 在PostgreSQL表中创建多个索引的缺点

database – 在PostgreSQL表中创建多个索引的缺点

读完 documentation on indexes后我想

嘿,因为(在我的情况下)几乎总是从数据库读取比写入它更频繁地执行,为什么不在表中的大多数字段上创建索引?

这是正确的态度吗?除了插入更长时,还有其他任何缺点吗?

当然,索引将仅限于我在SELECT语句条件下实际使用的字段.

解决方法

索引有几个缺点.
首先,他们消耗空间.这可能是无关紧要的,但如果您的桌子特别大,可能会产生影响.
其次,更重要的是,您需要记住索引在INSERTing新行,删除旧行或UPDATEing索引列的现有值时会有性能损失,因为现在DML语句不仅需要修改表的数据,而且指数也是一个.再次,这在很大程度上取决于您的应用程序用例.如果DML非常罕见以至于性能不成问题,那么这可能不是一个考虑因素.
第三(虽然这与我的第一点紧密相关),请记住,每次创建另一个数据库对象时,都会产生额外的维护开销 – 这是您必须偶尔重建的另一个索引,收集统计信息(取决于RDBMS)你正在使用的另一个目标是打击数据字典等.

底线全部归结为您的用例.如果您有经常运行的重要查询,并且可以通过此索引进行改进 – 那就去做吧.如果您在蓝色月亮中运行此查询一次,您可能不希望减慢所有INSERT语句的速度.

database – 如何在一个表中创建多个序列?

database – 如何在一个表中创建多个序列?

我有一张桌子“收据”.我有列customer_id(谁有收据)和receipt_number.对于每个客户,receipt_number应该从1开始并且是序列.这意味着customer_id和receipt_number将是唯一的.我怎样才能优雅地做到这一点.我可以使用CREATE SEQUENCE或类似的内置序列功能吗?似乎我必须为每个客户创建一个序列,这当然不是一个优雅的解决方案.

编辑:必须有一个线程安全和白痴安全的方法来做到这一点.这应该是一个非常简单/普遍的需求.

解决方法

SEQUENCE不保证没有差距.例如,一个事务可能会生成一个新数字然后中止(由于错误或电源故障或其他…).然后,下一个交易将盲目地获得下一个数字,而不是那个“丢失”的数字.

如果您的客户应用程序不依赖于第一个地方的“无间隙”假设,那将是最好的.但是,您可以最大限度地减少这样的差距:

> SELECT MAX(receipt_number)FROM收据WHERE customer_id =:ci
> INSERT INTO收据(customer_id,receipt_number)VALUES(:ci,aboveresult 1),如果步骤1返回NULL,则只插入1.
>如果步骤2返回PK违规*,则从头开始重试.

*因为并发事务已经过同一个进程并已提交.

只要添加行而不删除行,即使在并发环境中也可以防止出现任何间隙.

顺便说一下,你可以像这样“压缩”第1步和第2步:

INSERT INTO receipts (customer_id,receipt_number)
SELECT :ci,COALESCE(MAX(receipt_number),0) + 1
FROM receipts
WHERE customer_id = :ci;

[SQL Fiddle]

PK {customer_id,receipt_number}下面的索引应确保有效满足此查询的SELECT部分​​.

Groupby 移位(滞后值)模拟,只有 Numpy(无熊猫) 对虚拟数据进行测试 -

Groupby 移位(滞后值)模拟,只有 Numpy(无熊猫) 对虚拟数据进行测试 -

IIUC,您希望完全在 numpy 中实现 df.groupby('id')['v1'].shift(-1)。这是由石斑鱼和移位法组成。

一个 groupby() 在 numpy 中等效于具有第一分组列和第二个值列的二维数组是 -

np.split(arr[:,1],np.unique(arr[:,0],return_index=True)[1][1:])

在 numpy 中,一维数组的 shift() 等价物是 -

np.append(np.roll(arr,-1)[:-1],np.nan)

把这两个放在一起,你就能得到你想要的-

#2D array with only id and v1 as columns
arr = df[['id','v1']].values   

#Groupby based on id
grouper = np.split(arr[:,return_index=True)[1][1:]) 

#apply shift to grouped elements
shift = [np.append(np.roll(i,np.nan) for i in grouper] 

#stack them as a single array
new_col = np.hstack(shift) 

#set as column
df['shifted'] = new_col 

对虚拟数据进行测试 -

#Dummy data
idx = [0,1,2,3,3]
val = np.arange(len(idx))
arr = np.array([idx,val]).T
df = pd.DataFrame(arr,columns=['id','v1'])

#apply grouped shifting
arr = df[['id','v1']].values
grouper = np.split(arr[:,return_index=True)[1][1:])
shift = [np.append(np.roll(i,np.nan) for i in grouper]
new_col = np.hstack(shift)
df['shifted'] = new_col

print(df)
    id  v1  shifted
0    0   0      1.0
1    0   1      2.0
2    0   2      3.0
3    0   3      4.0
4    0   4      NaN
5    1   5      6.0
6    1   6      7.0
7    1   7      8.0
8    1   8      9.0
9    1   9     10.0
10   1  10      NaN
11   2  11     12.0
12   2  12     13.0
13   2  13     14.0
14   2  14      NaN
15   3  15     16.0
16   3  16     17.0
17   3  17     18.0
18   3  18     19.0
19   3  19      NaN

Pandas无法读取在PySpark中创建的实木复合地板文件

Pandas无法读取在PySpark中创建的实木复合地板文件

我正在通过以下方式从Spark DataFrame编写镶木地板文件:

df.write.parquet("path/myfile.parquet", mode = "overwrite", compression="gzip")

这将创建一个包含多个文件的文件夹。

当我尝试将其读入pandas时,会出现以下错误,具体取决于我使用的解析器:

import pandas as pddf = pd.read_parquet("path/myfile.parquet", engine="pyarrow")

PyArrow:

pyarrow.lib.check_status中的文件“ pyarrow \ error.pxi”,第83行

ArrowIOError:无效的实木复合地板文件。页脚已损坏。

快速镶木地板:

文件“ C:\ Program Files \ Anaconda3 \ lib \ site-packages \ fastparquet \
util.py”,行38,在default_open中返回open(f,mode)

PermissionError:[Errno 13]权限被拒绝:’path / myfile.parquet’

我正在使用以下版本:* Spark 2.4.0* Panda 0.23.4* Poppy 0.10.0* Fast parquet 0.2.1

我尝试了gzip以及灵活的压缩。两者都不起作用。我当然要确保文件位于Python有权读取/写入的位置。

如果有人能够重现此错误,则已经有所帮助。

答案1

小编典典

由于即使使用较新的pandas版本,这似乎仍然是一个问题,因此我编写了一些函数来规避此问题,这是更大的pyspark helpers库的一部分:

import pandas as pdimport datetimedef read_parquet_folder_as_pandas(path, verbosity=1):  files = [f for f in os.listdir(path) if f.endswith("parquet")]  if verbosity > 0:    print("{} parquet files found. Beginning reading...".format(len(files)), end="")    start = datetime.datetime.now()  df_list = [pd.read_parquet(os.path.join(path, f)) for f in files]  df = pd.concat(df_list, ignore_index=True)  if verbosity > 0:    end = datetime.datetime.now()    print(" Finished. Took {}".format(end-start))  return dfdef read_parquet_as_pandas(path, verbosity=1):  """Workaround for pandas not being able to read folder-style parquet files.  """  if os.path.isdir(path):    if verbosity>1: print("Parquet file is actually folder.")    return read_parquet_folder_as_pandas(path, verbosity)  else:    return pd.read_parquet(path)

这假定拼花地板“文件”中的相关文件(实际上是一个文件夹)以“
.parquet”结尾。这适用于数据砖导出的拼花文件,也可以与其他文件一起使用(未经测试,对评论中的反馈感到高兴)。

read_parquet_as_pandas()如果事先不知道是否为文件夹,则可以使用该功能。

关于在pandas中创建多个移位滞后列的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于database – 在PostgreSQL表中创建多个索引的缺点、database – 如何在一个表中创建多个序列?、Groupby 移位(滞后值)模拟,只有 Numpy(无熊猫) 对虚拟数据进行测试 -、Pandas无法读取在PySpark中创建的实木复合地板文件等相关知识的信息别忘了在本站进行查找喔。

本文标签: