在Python Pandas中将列向左对齐

  • Post category:Python

在Pandas中,可以使用format()方法调整数据的格式,从而实现将列向左对齐的效果。具体步骤如下:

  1. 读取数据,并使用df.columns获取数据集中所有的列名。

  2. 使用列表推导式遍历所有的列名,将每个列名转换成一个带有'<‘格式化符号的字符串。'<‘表示数据左对齐。

python
df.columns = [f"{i:<10}" for i in df.columns]

  1. 将数据按格式进行输出,这里使用了pandas的to_string()方法,并在其选项中设置了’justify’参数为’left’,表示左对齐。

python
print(df.to_string(index=False, justify='left'))

完整代码如下:

import pandas as pd

# 读取数据
df = pd.read_csv('data.csv')

# 将列名向左对齐
df.columns = [f"{i:<10}" for i in df.columns]

# 将数据向左对齐输出
print(df.to_string(index=False, justify='left'))

这样就可以将Pandas数据集中的列向左对齐了。