pandas - 在列值的基础上添加缺失的行以获得 linspace
pandas - add missing rows on the basis of column values to have linspace
我有一个 pandas 数据框
a b c
0 0.5 10 7
1 1.0 6 6
2 2.0 1 7
3 2.5 6 -5
4 3.5 9 7
并且我想在某个步骤的基础上填充关于列 'a' 的缺失列。在这种情况下,给定步长0.5,我想用缺失值填充'a'列,即1.5和3.0,并将其他列设置为空,以获得以下结果。
a b c
0 0.5 10.0 7.0
1 1.0 6.0 6.0
2 1.5 NaN NaN
3 2.0 1.0 7.0
4 2.5 6.0 -5.0
5 3.0 NaN NaN
6 3.5 9.0 7.0
使用 pandas 或 numpy 或 scipy 等其他库执行此操作的最简洁方法是什么?
谢谢!
创建数组 numpy.arange
, then create index
by set_index
and last reindex
with reset_index
:
step= .5
idx = np.arange(df['a'].min(), df['a'].max() + step, step)
df = df.set_index('a').reindex(idx).reset_index()
print (df)
a b c
0 0.5 10.0 7.0
1 1.0 6.0 6.0
2 1.5 NaN NaN
3 2.0 1.0 7.0
4 2.5 6.0 -5.0
5 3.0 NaN NaN
6 3.5 9.0 7.0
一个简单的实现方法是首先创建您想要的索引,然后合并其中的剩余信息:
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [0.5, 1, 2, 2.5, 3.5],
'b': [10, 6, 1, 6, 9],
'c': [7, 6, 7, -5, 7]})
ls = np.arange(df.a.min(), df.a.max(), 0.5)
new_df = pd.DataFrame({'a':ls})
new_df = new_df.merge(df, on='a', how='left')
我有一个 pandas 数据框
a b c
0 0.5 10 7
1 1.0 6 6
2 2.0 1 7
3 2.5 6 -5
4 3.5 9 7
并且我想在某个步骤的基础上填充关于列 'a' 的缺失列。在这种情况下,给定步长0.5,我想用缺失值填充'a'列,即1.5和3.0,并将其他列设置为空,以获得以下结果。
a b c
0 0.5 10.0 7.0
1 1.0 6.0 6.0
2 1.5 NaN NaN
3 2.0 1.0 7.0
4 2.5 6.0 -5.0
5 3.0 NaN NaN
6 3.5 9.0 7.0
使用 pandas 或 numpy 或 scipy 等其他库执行此操作的最简洁方法是什么?
谢谢!
创建数组 numpy.arange
, then create index
by set_index
and last reindex
with reset_index
:
step= .5
idx = np.arange(df['a'].min(), df['a'].max() + step, step)
df = df.set_index('a').reindex(idx).reset_index()
print (df)
a b c
0 0.5 10.0 7.0
1 1.0 6.0 6.0
2 1.5 NaN NaN
3 2.0 1.0 7.0
4 2.5 6.0 -5.0
5 3.0 NaN NaN
6 3.5 9.0 7.0
一个简单的实现方法是首先创建您想要的索引,然后合并其中的剩余信息:
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [0.5, 1, 2, 2.5, 3.5],
'b': [10, 6, 1, 6, 9],
'c': [7, 6, 7, -5, 7]})
ls = np.arange(df.a.min(), df.a.max(), 0.5)
new_df = pd.DataFrame({'a':ls})
new_df = new_df.merge(df, on='a', how='left')