pandas 的日期时间列乘以数字
datetime column of pandas multiply a number
我有一个带有字符串类型的日期时间列的数据框,如下所示:
>>> df2
date a b
0 2020/1/1 8.0 5.0
1 2020/1/2 10.0 7.0
2 2020/1/3 6.0 1.0
3 2020/1/4 6.0 3.0
我想使用它的 'date' 列通过乘以数组来生成具有不同长度的新索引,如下所示:
>>> idx_list = [2,3,1,2]
>>> df2.date*idx_list
但我得到了意想不到的结果:
>>> df2.date*idx_list
0 2020/1/12020/1/1
1 2020/1/22020/1/22020/1/2
2 2020/1/3
3 2020/1/42020/1/4
有没有办法让新的索引系列成为顺序数据,比如:
0 2020/1/1
1 2020/1/1
2 2020/1/2
3 2020/1/2
4 2020/1/2
5 2020/1/3
6 2020/1/4
7 2020/1/4
谢谢!
试试这个
df2 = pd.DataFrame({'date': ['2020/1/1', '2020/1/2', '2020/1/3', '2020/1/4'],
'a': [8.0, 10.0, 6.0, 6.0],
'b': [5.0, 7.0, 1.0, 3.0]})
idx_list = [2,3,1,2]
# use repeat
df2['date'].repeat(idx_list)
0 2020/1/1
0 2020/1/1
1 2020/1/2
1 2020/1/2
1 2020/1/2
2 2020/1/3
3 2020/1/4
3 2020/1/4
Name: date, dtype: object
如果你想让日期成为索引,那么试试这个
# make date the index
df2 = df2.set_index('date')
idx_list = [2,3,1,2]
use repeat and loc to create duplicated rows
df2 = df2.loc[df2.index.repeat(idx_list)]
print(df2)
a b
date
2020/1/1 8.0 5.0
2020/1/1 8.0 5.0
2020/1/2 10.0 7.0
2020/1/2 10.0 7.0
2020/1/2 10.0 7.0
2020/1/3 6.0 1.0
2020/1/4 6.0 3.0
2020/1/4 6.0 3.0
你可以尝试重复列表n次然后展开
idx_list = [2,3,1,2]
df = (df.assign(date=df['date'].apply(lambda x: [x]) * idx_list)
.explode('date'))
print(df)
date a b
0 2020/1/1 8.0 5.0
0 2020/1/1 8.0 5.0
1 2020/1/2 10.0 7.0
1 2020/1/2 10.0 7.0
1 2020/1/2 10.0 7.0
2 2020/1/3 6.0 1.0
3 2020/1/4 6.0 3.0
3 2020/1/4 6.0 3.0
我有一个带有字符串类型的日期时间列的数据框,如下所示:
>>> df2
date a b
0 2020/1/1 8.0 5.0
1 2020/1/2 10.0 7.0
2 2020/1/3 6.0 1.0
3 2020/1/4 6.0 3.0
我想使用它的 'date' 列通过乘以数组来生成具有不同长度的新索引,如下所示:
>>> idx_list = [2,3,1,2]
>>> df2.date*idx_list
但我得到了意想不到的结果:
>>> df2.date*idx_list
0 2020/1/12020/1/1
1 2020/1/22020/1/22020/1/2
2 2020/1/3
3 2020/1/42020/1/4
有没有办法让新的索引系列成为顺序数据,比如:
0 2020/1/1
1 2020/1/1
2 2020/1/2
3 2020/1/2
4 2020/1/2
5 2020/1/3
6 2020/1/4
7 2020/1/4
谢谢!
试试这个
df2 = pd.DataFrame({'date': ['2020/1/1', '2020/1/2', '2020/1/3', '2020/1/4'],
'a': [8.0, 10.0, 6.0, 6.0],
'b': [5.0, 7.0, 1.0, 3.0]})
idx_list = [2,3,1,2]
# use repeat
df2['date'].repeat(idx_list)
0 2020/1/1
0 2020/1/1
1 2020/1/2
1 2020/1/2
1 2020/1/2
2 2020/1/3
3 2020/1/4
3 2020/1/4
Name: date, dtype: object
如果你想让日期成为索引,那么试试这个
# make date the index
df2 = df2.set_index('date')
idx_list = [2,3,1,2]
use repeat and loc to create duplicated rows
df2 = df2.loc[df2.index.repeat(idx_list)]
print(df2)
a b
date
2020/1/1 8.0 5.0
2020/1/1 8.0 5.0
2020/1/2 10.0 7.0
2020/1/2 10.0 7.0
2020/1/2 10.0 7.0
2020/1/3 6.0 1.0
2020/1/4 6.0 3.0
2020/1/4 6.0 3.0
你可以尝试重复列表n次然后展开
idx_list = [2,3,1,2]
df = (df.assign(date=df['date'].apply(lambda x: [x]) * idx_list)
.explode('date'))
print(df)
date a b
0 2020/1/1 8.0 5.0
0 2020/1/1 8.0 5.0
1 2020/1/2 10.0 7.0
1 2020/1/2 10.0 7.0
1 2020/1/2 10.0 7.0
2 2020/1/3 6.0 1.0
3 2020/1/4 6.0 3.0
3 2020/1/4 6.0 3.0