繁体   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