将 Pandas 数据框拆分为多列 [英] Split a pandas dataframe into multiple columns
问题描述
目标
我有一个如下所示的 Pandas 数据框,我想在有空格的地方拆分它,将命令"和浮点值分开.
I have a pandas dataframe as shown below and would like to split it where there is a blank-space, separating the "command" and the float value.
数据框 - df
例如:
0
...
432 cl_bob_lower_amt "0"
433 cl_bobamt_lat "0"
434 cl_bobamt_vert "0"
435 cl_bobcycle "2"
436 cl_viewmodel_shift_left_amt "0"
437 cl_viewmodel_shift_right_amt "0"
...
<小时>
我的尝试
我尝试使用此处
import pandas as pd
file_ = open("E:\\Location\\Tree\\123456\\730\\local\\cfg\\myconfig.cfg", 'r')
content = file_.read()
paths = content.split("\n")
df = pd.DataFrame(paths)
df = pd.DataFrame(df.row.str.split(' ',1).tolist(),columns = ['command','value'])
print df
但是,我似乎收到以下错误:
However, I seem to be receiving the following error:
AttributeError: 'DataFrame' object has no attribute 'row'
很遗憾,我无法确定发生这种情况的原因.
Unfortunately I'm unable to identify why this occurs.
预期结果:
command value
...
432 cl_bob_lower_amt "0"
433 cl_bobamt_lat "0"
434 cl_bobamt_vert "0"
435 cl_bobcycle "2"
436 cl_viewmodel_shift_left_amt "0"
437 cl_viewmodel_shift_right_amt "0"
...
最终我希望用户能够搜索命令并更改值.
Ultimately I would like the user to be able to search for the command and change the value.
推荐答案
我猜您正在尝试为 DF 调用ROW"属性,但该属性不存在.如果您正在尝试执行选择行的操作,我建议 .itterows() 调用仅在选择索引处循环您想要的行!这是我认为您要实现的最佳解决方案:)
My guess is you are attempting to call the "ROW" attribute for the DF, which does not exist. If you are attempting to do operations to select rows, I would suggest the .itterows() call to loop over just the rows you want at select indexes! Here is the best solution for what I think you are trying to achieve :)
import pandas as pd
重新创建的虚拟数据
content = ['cl_bob_lower_amt "0"',
'cl_bobamt_lat "0"',
'cl_bobamt_vert "0"',
'cl_bobcycle "2"',
'cl_viewmodel_shift_left_amt "0"',
'cl_viewmodel_shift_right_amt "0"',]
原始数据框创建
df = pd.DataFrame(content, columns = ['Value'])
通过对 Value.str 使用 .split 调用创建一个新的数据帧(或重新分配给现有的 DF)
Create a new dataframe (or re-assign to existing DF) by using .split call on Value.str
split_df = pd.DataFrame(df.Value.str.split(" ").tolist(), columns=["Command", "Value"])
结果:
Command Value
0 cl_bob_lower_amt "0"
1 cl_bobamt_lat "0"
2 cl_bobamt_vert "0"
3 cl_bobcycle "2"
4 cl_viewmodel_shift_left_amt "0"
5 cl_viewmodel_shift_right_amt "0"
这篇关于将 Pandas 数据框拆分为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!