使用lambda或将其应用于具有列表内容的数据框的多列

时间:2019-06-03 19:33:03

标签: python pandas dataframe lambda

这可能是一个琐碎的问题。我有以下数据框,其中各列包含列表。

import pandas as pd
df = pd.DataFrame({'time1': [['2000', '2300'], ['1000', '1100']], 'time2': [['2200', '2400'], ['800', '900']]})
print(df)

  time1         time2
0  [2000, 2300]  [2200, 2400]
1  [1000, 1100]    [800, 900]

列表中的值表示时间间隔。我正在尝试将所有这些元素转换为时间格式。

我正在尝试得到这样的东西:

time1         time2
20:00-23:00  22:00-24:00
10:00-11:00  8:00-9:00

2 个答案:

答案 0 :(得分:1)

我们可以在此处定义函数以取消嵌套列表并用:分隔符分隔字符串,然后将其应用于每列:

functime = lambda x: '-'.join([t[:-2] + ':' + t[-2:] for t in x])

for col in df.columns:
    df[col] = df[col].apply(functime)

print(df)
         time1        time2
0  20:00-23:00  22:00-24:00
1  10:00-11:00    8:00-9:00

定义常规函数:

def functime2(x):
    val = '-'.join([t[:-2] + ':' + t[-2:] for t in x])

    return val

for col in df.columns:
    df[col] = df[col].apply(functime2)

         time1        time2
0  20:00-23:00  22:00-24:00
1  10:00-11:00    8:00-9:00

答案 1 :(得分:0)

这是基于this不可接受的答案的一种间接方法。这个想法是将字符串分为小时和分钟,然后使用破折号-:

import pandas as pd
df = pd.DataFrame({'time1': [['2000', '2300'], ['1000', '1100']], 
                   'time2': [['2200', '2400'], ['800', '900']]})


def convert_to_minutes(value):
    tim = []
    for val in value:
        hours, minutes = val[0:-2], val[-2:]
        tim.append(hours + ':' + minutes)

    return '-'.join(tim)

df['time1'] = df['time1'].apply(convert_to_minutes)
df['time2'] = df['time2'].apply(convert_to_minutes)

输出

print (df)

         time1        time2
 0  20:00-23:00  22:00-24:00
 1  10:00-11:00    8:00-9:00