簡體   English   中英

如何從 pandas 列創建列表

[英]How to create lists from pandas columns

我使用以下代碼創建了一個 pandas dataframe:

import numpy as np
import pandas as pd

ds = {'col1': [1,2,3,3,3,6,7,8,9,10]}


df = pd.DataFrame(data=ds)

dataframe 看起來像這樣:

print(df)

   col1
0     1
1     2
2     3
3     3
4     3
5     6
6     7
7     8
8     9
9    10

我需要創建一個名為col2的字段,該字段在列表(對於每條記錄)中包含 col1 的最后 3 個元素,同時遍歷每條記錄。 因此,生成的 dataframe 將如下所示:

在此處輸入圖像描述

有誰知道怎么做?

這是一個使用滾動和列表理解的解決方案

df['col2'] = [x.tolist() for x in df['col1'].rolling(3)]

   col1        col2
0     1         [1]
1     2      [1, 2]
2     3   [1, 2, 3]
3     3   [2, 3, 3]
4     3   [3, 3, 3]
5     6   [3, 3, 6]
6     7   [3, 6, 7]
7     8   [6, 7, 8]
8     9   [7, 8, 9]
9    10  [8, 9, 10]

使用列表理解:

N = 3
l = df['col1'].tolist()

df['col2'] = [l[max(0,i-N+1):i+1] for i in range(df.shape[0])]

Output:


   col1        col2
0     1         [1]
1     2      [1, 2]
2     3   [1, 2, 3]
3     3   [2, 3, 3]
4     3   [3, 3, 3]
5     6   [3, 3, 6]
6     7   [3, 6, 7]
7     8   [6, 7, 8]
8     9   [7, 8, 9]
9    10  [8, 9, 10]

看到其他答案后,我肯定我的答案很愚蠢。 不管怎樣,就在這里。

import pandas as pd
ds = {'col1': [1,2,3,3,3,6,7,8,9,10]}
df = pd.DataFrame(data=ds)
df['col2'] = df['col1'].shift(1)
df['col3'] = df['col2'].shift(1)
df['col4'] = (df[['col3','col2','col1']]
    .apply(lambda x:','.join(x.dropna().astype(str)),axis=1)
)

最后一列包含結果列表。

   col1          col4
0     1           1.0
1     2       1.0,2.0
2     3   1.0,2.0,3.0
3     3   2.0,3.0,3.0
4     3   3.0,3.0,3.0
5     6   3.0,3.0,6.0
6     7   3.0,6.0,7.0
7     8   6.0,7.0,8.0
8     9   7.0,8.0,9.0
9    10  8.0,9.0,10.0
lastThree = []
for x in range(len(df)):
    lastThree.append([df.iloc[x - 2]['col1'], df.iloc[x - 1]['col1'], df.iloc[x]['col1']])

df['col2'] = lastThree

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM