python - 使用行和列值将数据添加到数据框中
问题描述
我正在尝试使用行和列值将数据添加到数据框中,如下所示:
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”未排序。
如果有的话,请告诉我解决方法,或者请让我知道这样做的替代方法。提前致谢。
解决方案
我使用了一个列表来解决这个问题。最后,我将此列表列表转换为数据框。
推荐阅读
- css - 如何知道用户是否在css中使用移动设备?
- sql - 根据换算表进行单位换算的功能
- java - 当文件改变时,我读取文件,文件的内容总是一样的?
- c++ - D3DXCreateTextureFromFile 不创建纹理
- flutter - 如何在颤振中创建这种类型的对话框
- gmail - Gmail LodgingReservation 标记显示不正确的日期
- html - 锚标记无法正常工作。当我打开网页时,它的行为就像一个简单的文本而不是一个链接
- design-patterns - 查询对象——哪一层?
- vue.js - VUEJS“Vue Hotel Datepicker”默认显示日历折叠打开
- javascript - 如何根据日出和日落时间戳确定白天或夜间