问题描述
您可以帮助完成以下任务吗?我有一个数据框列,例如:
index df['Q0']
0 1
1 2
2 3
3 5
4 5
5 6
6 7
7 8
8 3
9 2
10 4
11 7
如果df.loc [0,'Q0'],我想用df.loc [0:2,'Q0']中的值替换df.loc [3:8,'Q0']中的值! = df.loc [3,'Q0']
结果应类似于以下内容:
index df['Q0']
0 1
1 2
2 3
3 1
4 2
5 3
6 1
7 2
8 3
9 2
10 4
11 7
我尝试了以下行:
df.loc[3:8,'Q0'].where(~df.loc[0,'Q0']!=df.loc[3,'Q0']),other=df.loc[0:2,'Q0'],inplace=True)
或
df['Q0'].replace(to_replace=df.loc[3:8,value=df.loc[0:2,inplace=True)
但是它不起作用。我很可能在做错事。 有什么建议吗?
解决方法
您可以使用cycle函数:
from itertools import cycle
c = cycle(df["Q0"][0:3])
if df.Q0[0] != df.Q0[3]:
df["Q0"][3:8] = [next(c) for _ in range(5)]
,
感谢您的答复。我尝试了建议,但遇到了一些问题:
@adnanmuttaleb- 当我在具有多于1列(例如12x2或更大)的数据框中应用该函数时,我注意到df.Q0 [8]中的值没有变化。为什么?
@jezrael- 当我适应您的建议时,我得到了错误:
ValueError: cannot copy sequence with size 5 to array axis with dimension 6
将范围更改为6时,我得到了错误的结果
import pandas as pd
from itertools import cycle
data={'Q0':[1,2,3,5,6,7,8,4,7],'Q0_New':[0,0]}
df = pd.DataFrame(data)
##### version 1
c = cycle(df["Q0"][0:3])
if df.Q0[0] != df.Q0[3]:
df['Q0_New'][3:8] = [next(c) for _ in range(5)]
##### version 2
d = cycle(df.loc[0:3,'Q0'])
if df.Q0[0] != df.Q0[3]:
df.loc[3:8,'Q0_New'] = [next(d) for _ in range(6)]
为什么我们会有不同的行为,需要进行哪些更正?
再次感谢大家。