简体   繁体   English

Append 循环 output 列 pandas python

[英]Append loop output in column pandas python

I am working with the code below to append output to empty dataframe我正在使用下面的代码到 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)

i am getting output as below but i want我得到如下 output 但我想要

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

What i want the output to be我想要 output 是什么

        0    1       2
0   30708   15    1800
1   19200   50    1180

How can i make 3 rows to 3 columns every time the loop repeats.每次循环重复时,我怎样才能使 3 行到 3 列。

If x is a list of values, use:如果x是值列表,请使用:

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

to append all the values as a new row instead of appending a single element as a row.到 append 将所有值作为新行,而不是将单个元素作为行附加。 Look here for more details about the append method. 在此处查看有关 append 方法的更多详细信息。

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

you could first convert to numpy.ndarry in order to perform reshape():您可以先转换为 numpy.ndarry 以执行 reshape():

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

then back to pd.DataFrame if you really need it to be a pandas dataframe然后回到 pd.DataFrame 如果你真的需要它成为 pandas dataframe

df = pd.DataFrame(vals)

It perplexes me when you write x = y without doing any manipulation on x .当您编写x = y而不对x进行任何操作时,这让我感到困惑。 Seems like a redundant operation.似乎是一个多余的操作。 Another problem with your code is that image_data.append is slow since it has to copy the backing memory.您的代码的另一个问题是image_data.append很慢,因为它必须复制支持 memory。 Repeatedly calling it in a loop is a guarantee of performance bottleneck.在循环中反复调用它是性能瓶颈的保证。

Try this instead:试试这个:

# 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