重命名特定列并更改dtyp

2024-10-02 16:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df1,其中多个列包含相同的字符串子集。如何单独对这些列进行更改。例如,删除最后三个字符,更改列的数据类型,等等。我只是想更轻松地对具有相同字符子集的列进行更改(例如“Session”,如下所示)

第一个例子:

df1:

Session1    Session2    Session3    Total
3.0         4.0         5.0         5.0
2.0         1.0         4.0         NaN

df2 (Intended Output):

Session1    Session2    Session3    Total
3           4           5           5.0
2           1           4           Nan

第二个例子:

df1:

Session1    Session2    Session3    Total
3           4           5           5.0
2           1           4           Nan

df2 (Intended Out):

Sessi    Sessi    Sessi    Total
3        4        5        5.0
2        1        4        NaN

Tags: 数据字符串nan字符子集例子totaldf1
2条回答

关于你的第一点:

n_columns_with_session = 3
# create the names of the target columns
cols = ["Session{}".format(i) for i in range(1,n_columns_with_session+1)]

# change the dtype of the target columns
df1[cols] = df1[cols].astype('int64')


第二点:

# create the new names
new_names_cols = ["Sess{}".format(i) for i in range(1,n_columns_with_session+1)]

# append "Total" name since you do not want to change this
new_names_cols.append('Total')    

# rename the columns
df1.columns = new_names_cols

第一步是过滤所有需要的目标列。你可以用

target_cols = [col for col in df if col.startswith('Session')]

然后可以对这些列应用任何操作。例如,要更改数据类型,可以执行以下操作

df[target_cols] = df[target_cols].astype('int64')

编辑: 对于重命名和删除最后三个字符的第二点,您可以使用如下重命名函数:

new_cols = [i[:-3] for i in target_cols]
df.rename(columns=dict(zip(target_cols, new_cols)), inplace=True)

相关问题 更多 >