小写并替换 Pandas 中数据帧 header 中不需要的子字符串
Lowercase and replace unwanted substrings from dataframe header in Pandas
我想 lowercase
并从数据帧的 header 中删除第一个 s
:'id', 'sTitle', 'sSource', 'sDate', 'sAbstract', 'sStart_Time', 'sSite', 'sUrl'
.
预期的header会这样:'id', 'title', 'source', 'date', 'abstract', 'start_time', 'site', 'url'
我试过:df.columns = df.columns.str.lower().lstrip('s')
,它产生错误:AttributeError: 'Index' object has no attribute 'lstrip'
。
我怎样才能正确地做到这一点?谢谢。
你需要再写.str
:
df.columns = df.columns.str.lstrip('s').str.lower()
编辑:
与 OP 讨论后,这是最终的工作代码:
cols = ['sAbstract', 'sStart_Time']
df.columns = pd.Series(df.columns.tolist()).replace({k: k.lstrip('s').lower() for k in cols})
我想 lowercase
并从数据帧的 header 中删除第一个 s
:'id', 'sTitle', 'sSource', 'sDate', 'sAbstract', 'sStart_Time', 'sSite', 'sUrl'
.
预期的header会这样:'id', 'title', 'source', 'date', 'abstract', 'start_time', 'site', 'url'
我试过:df.columns = df.columns.str.lower().lstrip('s')
,它产生错误:AttributeError: 'Index' object has no attribute 'lstrip'
。
我怎样才能正确地做到这一点?谢谢。
你需要再写.str
:
df.columns = df.columns.str.lstrip('s').str.lower()
编辑:
与 OP 讨论后,这是最终的工作代码:
cols = ['sAbstract', 'sStart_Time']
df.columns = pd.Series(df.columns.tolist()).replace({k: k.lstrip('s').lower() for k in cols})