Pandas多列代表

2024-09-30 22:11:30 发布

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

我有df,如下所示,我将按列进行拆分

>>> df 
           ID      Started
0           NaN  20.06.2017  13:19:04
1           NaN  10.04.2018  04:48:32
2     WBTS-1509  06.11.2017  10:28:14
3     WBTS-1509  03.03.2018  10:12:29
4     WBTS-1117  07.03.2018  17:04:28
df['Started'].apply(lambda x: x.split(':')[0])
df['ID'].apply(lambda x: x.split('-')[1])

我想设置3个列表变量

col_names = ['ID' , 'Started']
splitby = ['-' , ':']
index_after_split = [1 , 0]

使用inplace = True使用一行进行拆分(避免循环)

请帮我做同样的事

谢谢


Tags: lambdaiddf列表indexnamescolnan
1条回答
网友
1楼 · 发布于 2024-09-30 22:11:30

我认为这里有必要使用^{}循环,并使用str[]索引:

for a,b,c, in zip(col_names, splitby, index_after_split):
    df[a] = df[a].str.split(b).str[c]
print (df)
     ID        Started
0   NaN  20.06.2017 13
1   NaN  10.04.2018 04
2  1509  06.11.2017 10
3  1509  03.03.2018 10
4  1117  07.03.2018 17

相关问题 更多 >