Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何还原数据帧中的值?_Python_Pandas - Fatal编程技术网

Python:如何还原数据帧中的值?

Python:如何还原数据帧中的值?,python,pandas,Python,Pandas,我有一个数据帧df,由两列x和y组成。我想选择数据帧值的一半,并以这种方式还原x和y的值se df x y 0 2557 7 1 2570 67 2 2564 27 3 2581 2578 4 2571 38 5 2565 11 6 2578 41 7 2577 44 8 2579 30 dftmp = d

我有一个数据帧
df
,由两列
x
y
组成。我想选择数据帧值的一半,并以这种方式还原
x
y
的值se

df
         x      y
    0   2557    7
    1   2570    67
    2   2564    27
    3   2581    2578
    4   2571    38
    5   2565    11
    6   2578    41
    7   2577    44
    8   2579    30

dftmp = df  #save original data frame
indeces = np.arange(0, len(df))   # list of index
shuffle(indeces)   # random shuffle
indeces = indeces[0: int(len(indeces) / 2) ]  # take half of random indeces  

df['x'][indeces] = dftmp['y'][indeces]  # x new = y original
df['y'][indeces] = dftmp['x'][indeces]  # y new = x original
我不知道为什么它只更改
y

    df

      x      y
0   2557    2557
1   2570    2570
2   2564    2564
3   2581    2581
4   38      38
5   2565    11
6   41      41
7   2577    44
8   2579    30

下面是一个简短的方法:

df.update(df.sample(frac=0.5).rename(columns={'y': 'x', 'x': 'y'}))

df
Out: 
        x       y
0  2557.0     7.0
1  2570.0    67.0
2  2564.0    27.0
3  2578.0  2581.0
4    38.0  2571.0
5  2565.0    11.0
6    41.0  2578.0
7  2577.0    44.0
8    30.0  2579.0

dftmp=df.copy()
如果您使用例如:df.to_dict()@asongtoruin why?@emax与我们共享您的数据帧,这将非常有帮助。快速搜索得出以下结论:这非常聪明@(谢谢你)