簡體   English   中英

Append 循環 output 列 pandas python

[英]Append loop output in column pandas python

我正在使用下面的代碼到 append output 以清空 dataframe

image_data = pd.DataFrame()

for i in words:
    y = re.findall('{} ([^ ]*)'.format(re.escape(i)), data)
    x = y
    image_data = image_data.append(x, ignore_index = True)

我得到如下 output 但我想要

        0
0   30708
1      15
2    1800
0   19200
1      50
2    1180

我想要 output 是什么

        0    1       2
0   30708   15    1800
1   19200   50    1180

每次循環重復時,我怎樣才能使 3 行到 3 列。

如果x是值列表,請使用:

image_data = image_data.append([x], ignore_index = True)

到 append 將所有值作為新行,而不是將單個元素作為行附加。 在此處查看有關 append 方法的更多詳細信息。

# replicating your dataframe
data = [30708, 15, 1800, 19200, 50, 1180]
df = pd.DataFrame(data)

您可以先轉換為 numpy.ndarry 以執行 reshape():

vals = df[0].values.reshape(2, 3)

然后回到 pd.DataFrame 如果你真的需要它成為 pandas dataframe

df = pd.DataFrame(vals)

當您編寫x = y而不對x進行任何操作時,這讓我感到困惑。 似乎是一個多余的操作。 您的代碼的另一個問題是image_data.append很慢,因為它必須復制支持 memory。 在循環中反復調用它是性能瓶頸的保證。

試試這個:

# image_data starts as a list
image_data = []

for i in words:
    y = re.findall('{} ([^ ]*)'.format(re.escape(i)), data)
    image_data.append(y)

# And it ends as a DataFrame
image_data = pd.DataFrame(image_data)

暫無
暫無

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

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