支持我们有以下数据框。
col1 col2 col3
0 one two three
1 one two three
2 one two three
3 one two three
4 one two three
我们试图将31列引入此数据框架,每列代表当月的一天。
llet说我们想精确地将其介绍在列之间。
我们如何实现?
要简单,引入的列可以从1到31。
启动源代码col2
其他可能的解决方案:
col3
输出:
import pandas as pd
src = pd.DataFrame({'col1': ['one', 'one', 'one', 'one','one'],
'col2': ['two', 'two', 'two', 'two','two'],
'col3': ['three', 'three', 'three', 'three','three'],
})
您可以使用
pd.concat([src.iloc[:, :2].assign(
**{str(col): 0 for col in range(1, 32)}), src['col3']], axis=1)
和重新排序列,如下所示:
col1 col2 1 2 3 4 5 6 7 8 ... 23 24 25 26 27 28 29 30 31 \
0 one two 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0
1 one two 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0
2 one two 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0
3 one two 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0
4 one two 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0
col3
0 three
1 three
2 three
3 three
4 three
[5 rows x 34 columns]
iloc
或全新的副本,请使用import numpy as np
# Create dataframe with 31 column and 5 rows
tmp = pd.DataFrame(np.zeros((5, 31)), columns=range(1, 32))
# Concat two dataframes and reorder columns as you like
df = pd.concat([src.iloc[:,:2], tmp, src.iloc[:, 2:]], axis=1)
: col1 col2 1 2 3 4 5 6 7 8 ... 23 24 25 26 \
0 one two 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
1 one two 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
2 one two 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
3 one two 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
4 one two 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
27 28 29 30 31 col3
0 0.0 0.0 0.0 0.0 0.0 three
1 0.0 0.0 0.0 0.0 0.0 three
2 0.0 0.0 0.0 0.0 0.0 three
3 0.0 0.0 0.0 0.0 0.0 three
4 0.0 0.0 0.0 0.0 0.0 three
[5 rows x 34 columns]
reindex
result
cols = list(src)
cols[2:2] = range(1,31+1)
df = src.reindex(columns=cols, fill_value=0)