将数据帧转换为要写入cfg fi的字符串

2024-09-24 22:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

目标

我有一个Pandas数据帧,如下所示,并且希望连接列commandvalue,同时将其转换回原始字符串格式以写入.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.

Tags: 文件数据字符串dfvaluebindcfgcommand
1条回答
网友
1楼 · 发布于 2024-09-24 22:29:57

你打电话之后

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_writeconfig

sensitivitycl_teamid_overhead_always的设置后面有值,但host_writeconfig没有,因此当pandas尝试在空白(该行中不存在)上拆分时,第一个值是host_writeconfig,第二个值是None对象。你知道吗

相关问题 更多 >