【发布时间】:2019-06-18 04:56:08
【问题描述】:
我有多个具有相同类型数据的 csv 文件要合并到行上以形成单个数据框,但某些行名称包含脏数据。
例如'.'在实际名称的末尾。 我尝试了以下代码-
for file in all_files:
temp = pd.read_csv(file, encoding = "unicode_escape")
temp = temp[['S.No.', 'Item', '2014-15']]
state = lambda x: x.split('-')
temp.rename(columns = {'2014-15':state(file)[1]}, inplace= True)
if file == all_files[0]:
all_states = temp.copy(deep=True)
else:
temp["Item"] = temp["Item"].str.replace("*", "")
all_states = pd.merge(all_states, temp, how = 'outer', on = ['S.No.', 'Item'])
del temp
我得到的输出是 -
S.No. 1 1.1 1.2 1.3 . . .
1.1。 --> 需要摆脱这些并将它们视为 1.1
被污染的 S.No.为单个列形成一个新行。我需要它与其他人在同一行。
我只想要最后一个'.'在要删除的字符串的末尾,而不是全部。
我尝试了以下方法来清理 S.No. :
temp["S.No."] = temp["S.No."].str.rstrip(".")
temp["S.No."] = temp["S.No."].str.replace(".$", "")
temp["S.No."] = re.sub(r".$", "", str(temp["S.No."]))
但它们都不起作用。
【问题讨论】:
-
试试
temp["S.No."] = temp["S.No."].astype(int)
标签: python regex python-3.x pandas dataframe