首页 > 解决方案 > 使用行和列值将数据添加到数据框中

问题描述

我正在尝试使用行和列值将数据添加到数据框中,如下所示:

random = len(list(df.columns))//2
append_str = "Column-"
test_list = range(1,random+1)
test_list = [str(x) for x in test_list]
Columns = [append_str + sub for sub in test_list]
#op_df should have exactly half the length as that of df
op_df = pd.DataFrame(columns=Columns)
for row in rows:
    for col in cols:
       op_df[f"Column-{col+1}"][row] = df[f"Column-{2*col+1}"][row]
print(op_df)

上面的代码向我抛出了这个错误:
KeyError: 0
IndexError: index 0 is out of bounds for axis 0 with size 0

请注意,列表“rows”和“cols”未排序。

如果有的话,请告诉我解决方法,或者请让我知道这样做的替代方法。提前致谢。

标签: pythonpython-3.xpandas

解决方案


我使用了一个列表来解决这个问题。最后,我将此列表列表转换为数据框。


推荐阅读