[英]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 列。
# 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.