如何在 for 循环中将 np.arrays 连接到 DataFrame 中?

问题描述 投票:0回答:1

将 np.arrays 附加到 DataFrame 时出现错误。每个 np.array 都有不同的长度,因此 np.vstack 将不起作用。处理这个问题的最佳方法是什么?

另外,“y”需要进行相应的排序,并且我处理的数据具有不同的初始点 --- 我认为在 DataFrame 中排序更容易,但我还没有达到这一点。除非有其他建议?谢谢!

# For example:

# In "n" loop, I will get y0, x0. Then in "n+1" loop, I will get y1, x1 and "n+1" loop to get y2, x2, etc.
y0 = np.array([6,7,8,9])
y1 = np.array([1,2,3,4,5])
x0 = np.array([600, 700, 800, 900])
x1 = np.array([0.1, 0.2, 0.3, 0.4, 0.5])

# Ultimately, the DataFrame should return this:
print(df)

   y    x  
0  1    0.1
1  2    0.2
2  3    0.3
3  4    0.4
4  5    0.5
5  6    600
6  7    700
7  8    800
8  9    900

我当前的代码:

df = pd.DataFrame({"data_y":[], "data_x":[]})

for i in range(100):
    
    # Initiate lists
    data_y = []
    data_x = []

    # Data processed using list
    data_y, data_x = ....

    # Convert list to np.array
    data_y, data_x = ....

    # Compile data to DataFrame
    df["data_y"] = data_y.tolist()
    df["data_x"] = data_x.tolist()

# ValueError: Length of values (111) does not match length of index (256)
python arrays pandas numpy
1个回答
0
投票

代码中的问题是它每次都会删除

df 
的值。

您可以使用

df
data_x
在每次迭代中创建一个
data_y
并将其存储在列表中。最后连接所有结果。

import numpy as np
import pandas as pd


def processed_data():
  # your logic
  return [1, 3, 5], [0.2, 0.4, 0.6]

dfs_list = []
for i in range(3):
    data_x, data_y = processed_data()
    dfs_list.append(
        pd.DataFrame({"data_y": data_y, "data_x": data_x})
    )

df = pd.concat(dfs_list) 


print(df)

输出:

   data_y  data_x
0     0.2       1
1     0.4       3
2     0.6       5
0     0.2       1
1     0.4       3
2     0.6       5
0     0.2       1
1     0.4       3
2     0.6       5
© www.soinside.com 2019 - 2024. All rights reserved.