删除Pandas DataFrame.to_string插入的列之间的自动两个空格 [英] Remove the automatic two spaces between columns that Pandas DataFrame.to_string inserts
问题描述
I'm looking for a solution to remove/turn off the 2 spaces between columns that df.to_string
creates automatically.
示例:
from pandas import DataFrame
df = DataFrame()
df = df.append({'a':'12345', 'b': '12345'})
df.to_string(index=False, header=False)
'12345 1235'
为清楚起见,结果为:'12345..12345',其中点表示实际空间.
For clarity, the result is: '12345..12345' where the dots represent actual spaces.
我已经尝试过 pandas.set_option
和 pandas.to_string
文档.
I already tried the pandas.set_option
and pandas.to_string
documentation.
上面的示例过于简化.我正在与一个现有的df一起使用,该df到处都有空格,并且输出文本文件由另一个基于每个行的字符宽度的黑盒程序使用.我已经想出了如何使用格式化程序重新格式化列,并确保我的列没有被熊猫默认设置切除,所以我在那里的比例是90%(减去这些自动空格).仅供参考,以下是有关 to_string()
格式和数据截断的一些很好的链接:
The above example is overly simplified. I am working with an existing df that has spaces all over the place and the output text files are consumed by another blackbox program that is based off char-widths for each line. I've already figured out how to reformat the columns with formatters and make sure my columns are not cutoff by pandas default so I am 90% there (minus these auto spaces).
FYI here are some good links on to_string()
formatting and data-truncation:
感谢帮助!
推荐答案
您可以使用 pd.Series.str.cat
方法,该方法接受 sep
关键字参数.默认情况下, sep
设置为''
,因此值之间没有分隔.这里是文档: https://pandas.pydata.org/pandas-docs/stable/generation/pandas.Series.str.cat.html
You can use the pd.Series.str.cat
method, which accepts a sep
keyword argument. By default sep
is set to ''
so there is no separation between values. Here are the docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html
您还可以使用 pd.Series.str.strip
从每个值中删除任何前导或尾随空格.这里是文档: https://pandas.pydata.org/pandas-docs/stable/generation/pandas.Series.str.strip.html
You can also use pd.Series.str.strip
to remove any leading or trailing whitespace from each value. Here are the docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html
以下是基于您所拥有的示例:
Here's an example based on what you have:
df = pd.DataFrame({'a': ['12345'], 'b': ['12345']})
df.iloc[0].fillna('').str.strip().str.cat(sep=' ')
请注意,如果有任何空值,则需要 fillna('')
.
Note that fillna('')
is required if there are any empty values.
这篇关于删除Pandas DataFrame.to_string插入的列之间的自动两个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!