目标
我有一个Pandas数据框架,如下所示,并希望加入列、command和value,同时将其转换回原始字符串格式,以便写入.cfg文件。
数据帧- df
加入前:
command value
0 bind "0" "slot10"
1 bind "1" "slot1"
2 bind "2" "slot2"
3 bind "3" "slot3"
4 bind "4" "slot4"
5 bind "5" "slot5"
6 bind "6" "slot6"
7 bind "7" "slot7"
8 bind "8" "slot8"
9 bind "9" "slot9"
10 bind "a" "+moveleft"
11 bind "b" "buymenu"
12 bind "d" "+moveright"加入后:
0 bind "0" "slot10"
1 bind "1" "slot1"
2 bind "2" "slot2"
3 bind "3" "slot3"
4 bind "4" "slot4"
5 bind "5" "slot5"
6 bind "6" "slot6"
7 bind "7" "slot7"
8 bind "8" "slot8"
9 bind "9" "slot9"
10 bind "a" "+moveleft"
11 bind "b" "buymenu"
12 bind "d" "+moveright"
13 bind "e" "+use"
14 bind "f" "+lookatweapon"
...
etc.
dtype: object我的尝试
我已经成功地组合了两列,以便使用以下代码获得上面的输出:
df = df['command'].astype(str)+' '+df['value'].astype(str)但是,这仍然无助于将数据文件转换为原始字符串,以便可以将其写入.cfg文件。
我也尝试过使用df.to_string(),但这似乎没有什么区别
预期输出
我希望获得原始字符串输出,就像在变量下面分配的那样,要写入到.cfg文件中:
bind "0" "slot10"
bind "1" "slot1"
bind "2" "slot2"
bind "3" "slot3"
bind "4" "slot4"
bind "5" "slot5"
bind "6" "slot6"
bind "7" "slot7"
bind "8" "slot8"
bind "9" "slot9"
bind "a" "+moveleft"
bind "b" "buymenu"
bind "d" "+moveright"
bind "e" "+use"
bind "f" "+lookatweapon"
...
etc.发布于 2018-07-16 20:47:39
在你打电话后
df = df['command'].astype(str)+' '+df['value'].astype(str)实际上只剩下一个Series对象,所以您可以调用df.tolist(),然后用换行符连接列表中的元素。就像这样
s = df['command'].astype(str)+' '+df['value'].astype(str)
cfg_output = '\n'.join(s.tolist()) # joins each command with a newline因为您在原始配置文件中读取的方式,所以在最后一行中附加了一个None值
df = pd.DataFrame(df[0].str.split(' ',1).tolist(),columns = ['command','value'])无法计算没有值的配置设置。考虑原始conf文件的最后三行。
sensitivity "0.9"
cl_teamid_overhead_always 1
host_writeconfigsensitivity和cl_teamid_overhead_always的设置都有跟随它们的值,但是host_writeconfig没有,所以当熊猫试图在空格(在该行中不存在)拆分时,第一个值是host_writeconfig,第二个值是None对象。
https://stackoverflow.com/questions/51369727
复制相似问题