【问题标题】:How to add a new column in the middle of the dataframe with values based on the previous column?如何在数据框中间添加一个新列,其值基于前一列?
【发布时间】:2020-09-16 21:01:14
【问题描述】:

所以,我对 python 和 pandas 真的很陌生。 我有一个如下所示的数据框:

因此,在创建日期时间列之后,我想再添加三列“创建时间”、“创建星期几”、“创建月份”,它们基于“创建”中的日期和时间值日期时间”列。

例如,“Creation Time of Day”将包含“Morning”、“Evening”等值,具体取决于时间。 “Creation Day of Week”将包含“Monday”、“Tuesday”等值,“Creation Month”将包含“January”、“February”等值。我该怎么做?

【问题讨论】:

  • Creation Time of Day 的逻辑是什么?你能说得更具体点吗?
  • 它在一些时间序列分析中可以用作固定效应。他可能希望创建一些分类变量来显示是早上、中午还是晚上?
  • 是的,这就是我想要做的。将日期时间更改为分类值。

标签: python pandas dataframe


【解决方案1】:

用途:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'Creation Date-Time':pd.date_range('2015-01-02 15:07:01',periods=6,freq='231H')
                                 .strftime('%Y-%m-%dT%H:%M:%S'),
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})
print (df)
   A  B   Creation Date-Time  D  E  F
0  a  4  2015-01-02T15:07:01  1  5  a
1  b  5  2015-01-12T06:07:01  3  3  a
2  c  4  2015-01-21T21:07:01  5  6  a
3  d  5  2015-01-31T12:07:01  7  9  b
4  e  5  2015-02-10T03:07:01  1  2  b
5  f  4  2015-02-19T18:07:01  0  4  b

首先使用to_datetime作为日期时间,然后通过Index.get_loc获取Creation Date-Time列的位置,用于指定DataFrame.insert创建的新列的位置。对于分类使用cut,对于日期和月份的名称使用Series.dt.day_nameSeries.dt.month_name

df['Creation Date-Time'] = pd.to_datetime(df['Creation Date-Time'])

idx = df.columns.get_loc('Creation Date-Time')

#https://stackoverflow.com/a/55571425/2901002
b = [0,4,8,12,16,20,24]
l = ['Late Night', 'Early Morning','Morning','Noon','Eve','Night']
s = pd.cut(df['Creation Date-Time'].dt.hour, bins=b, labels=l)

df.insert(idx + 1, 'Creation Time of Day', s)
df.insert(idx + 2, 'Creation Time of Week', df['Creation Date-Time'].dt.day_name())
df.insert(idx + 3, 'Creation Month', df['Creation Date-Time'].dt.month_name())
print (df)

   A  B  Creation Date-Time Creation Time of Day Creation Time of Week  \
0  a  4 2015-01-02 15:07:01                 Noon                Friday   
1  b  5 2015-01-12 06:07:01        Early Morning                Monday   
2  c  4 2015-01-21 21:07:01                Night             Wednesday   
3  d  5 2015-01-31 12:07:01              Morning              Saturday   
4  e  5 2015-02-10 03:07:01           Late Night               Tuesday   
5  f  4 2015-02-19 18:07:01                  Eve              Thursday   

  Creation Month  D  E  F  
0        January  1  5  a  
1        January  3  3  a  
2        January  5  6  a  
3        January  7  9  b  
4       February  1  2  b  
5       February  0  4  b  

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2022-12-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 2022-11-21
    • 2020-12-20
    相关资源
    最近更新 更多