python-将中间值插入数据帧
所以我是熊猫队的新手,我正在尝试将我的旧代码转换为数据帧和系列。我的数据框如下所示:python-将中间值插入数据帧,python,pandas,Python,Pandas,所以我是熊猫队的新手,我正在尝试将我的旧代码转换为数据帧和系列。我的数据框如下所示: time data param t0 -1 x t1 0 z t2 -1 y t3 1 x t4 -1 y import pandas as pd df = pd.read_csv(pd.io.common.StringIO("""time data param t0 -1
time data param
t0 -1 x
t1 0 z
t2 -1 y
t3 1 x
t4 -1 y
import pandas as pd
df = pd.read_csv(pd.io.common.StringIO("""time data param
t0 -1 x
t1 0 z
t2 -1 y
t3 1 x
t4 -1 y"""), sep='\s+')
df['count'] = arange(df.shape[0])
df
我需要为每个1到-1和-1到1转换插入中间行。此行应包含回填时间和参数,数据值应为零
这是该操作后的外观:
time data param
t0 -1 x
t1 0 z
t2 -1 y
t3 0 x <-- added row
t3 1 x
t4 0 y <-- added row
t4 -1 y
查找1->1和-1->1转换,对它们进行计数,更改索引值,使用全范围重新索引以引入缺少的行
df.index += (df.data * df.data.shift() < 0).astype(int).cumsum()
df = df.reindex(arange(df.index[-1] + 1))
我仍在寻找更好的解决方案。请分享您的想法。您可以这样做:
time data param
t0 -1 x
t1 0 z
t2 -1 y
t3 1 x
t4 -1 y
import pandas as pd
df = pd.read_csv(pd.io.common.StringIO("""time data param
t0 -1 x
t1 0 z
t2 -1 y
t3 1 x
t4 -1 y"""), sep='\s+')
df['count'] = arange(df.shape[0])
df
设置从-1到1以及从-1到1的更改过滤器:
d1to_1 = (df.data == -1) & (df.data.shift() == 1)
d_1to1 = (df.data == 1) & (df.data.shift() == -1)
将数据复制到新的数据帧(以避免设置CopyWarning):
根据需要修改新数据,更改计数器以确保新行高于旧行:
df_1to1['data'] = 0
df_1to1['count'] = df_1to1['count'] - 1
df1to_1['data'] = 0
df1to_1['count'] = df1to_1['count'] - 1
连接新旧数据帧,按时间和计数器排序,然后重置索引
df = pd.concat([df, df1to_1, df_1to1], ignore_index=True).sort(['time','count']).reset_index(drop=True)
del df['count']
df
这将产生所需的输出:
time data param
0 t0 -1 x
1 t1 0 z
2 t2 -1 y
3 t3 0 x
4 t3 1 x
5 t4 0 y
6 t4 -1 y
如果您可以接受新行在旧行之后的情况,那么您可以跳过计数器
部分
time data param
0 t0 -1 x
1 t1 0 z
2 t2 -1 y
3 t3 0 x
4 t3 1 x
5 t4 0 y
6 t4 -1 y