繁体   English   中英

如何显示 Python 中一列的前 5 个字符?

[英]How to show first 5 characters within a column in Python?

需要 Zip 列只显示前 5 个字符

结果:

在此处输入图像描述

预期结果:

在此处输入图像描述

源代码:

import pandas as pd
import numpy as np #numpy is the module which can replace errors from huge datasets 
from openpyxl import load_workbook
from openpyxl.styles import Font

df_1 = pd.read_csv('correctional_facilities.csv')
df_2 = pd.read_csv('ems.csv')
df_3 = pd.read_csv('prt_hospital_space.csv')
df_4 = pd.read_csv('ec_hospital_space.csv')
df_5 = pd.read_csv('government.csv')
df_6 = pd.read_csv('fire.csv')
df_7 = pd.read_csv('prt_community_space.csv')
df_8 = pd.read_csv('ec_community_space_part1.csv')
df_9 = pd.read_csv('ec_community_space_part2.csv')
df_10 = pd.read_csv('police_facilities.csv')
df_11 = pd.read_csv('schools.csv')
df_12 = pd.read_csv('surgery_center.csv')

df_all = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12], sort=False) #this combines the sheets from 1,2,3 and the sort function as false so our columns stay in the same order

df_all.rename(columns={'Territory Assigned': 'Territory_Name', 'Treatment Region': 'Region_Name', '⭐ Customer Type': 'Customer_Type'}, inplace=True) #this renames the column headers to readable columns for axtria

df_all = df_all.replace(np.nan, 'N/A', regex=True) #replaces blanks/errors with N/A

remove = ['Country', 'Action'] #this will remove all unwanted columns
df_all.drop(columns=remove, inplace=True)

df_all['Zip'].str[:5] #this will only have 5 numbers for the zip code

您没有将切片字符串分配回 dataframe。您只需将df_all['Zip'].str[:5]替换为df_all['Zip'] = df_all['Zip'].str[:5]

例子:

>>> import pandas as pd
>>> data = [["Alice"],["Bob"],["Eve"]]
>>> df = pd.DataFrame(data,columns=['Name'])
>>> df
Name
0  Alice
1    Bob
2    Eve
>>> df['Name'].str[::-1]
0    ecilA
1      boB
2      evE
>>> df
# It didn't stick....
Name
0  Alice
1    Bob
2    Eve
>>> df['Name'] = df['Name'].str[::-1]
>>> df
# That's better
Name
0  ecilA
1    boB
2    evE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM