简体   繁体   English

交换 PANDAS 数据帧中的元素

[英]Swapping of elements in a PANDAS dataframe

Given below is a table :下面给出了一个表格:

    A NUMBER    B NUMBER
    7042967611  9999574081
    12320       9999574081
    9999574081  9810256463
    9999574081  9716551924
    9716551924  9999574081  
    9999574081  8130945859

This was originally an excel sheet which has been converted into a dataframe.这最初是一个已转换为数据框的 excel 表。 I wish to swap some of the elements such that the A number column has only 9999574081. Therefore the output should look like :我希望交换一些元素,使 A 数字列只有 9999574081。因此输出应如下所示:

    A NUMBER    B NUMBER
    9999574081  7042967611  
    9999574081  12320       
    9999574081  9810256463
    9999574081  9716551924
    9999574081  9716551924  
    9999574081  8130945859

This is the code I have used :这是我使用的代码:

for i in list(df['A NUMBER']):
    j=0
    if i!= 9999574081:
        temp = df['B NUMBER'][j]
        df['B NUMBER'][j] = i
        df['A NUMBER'][j] = temp
    j+=1

However, I am not getting the desired result.但是,我没有得到想要的结果。 Please help me out.请帮帮我。 Thanks:)谢谢:)

Use DataFrame.loc for swap only rows matched boolean mask, values is necessary for avoid align index values:使用DataFrame.loc仅交换匹配布尔掩码的行, values是必要的,以避免对齐索引值:

m = df['A NUMBER'] != 9999574081

df.loc[m, ['A NUMBER','B NUMBER']] = df.loc[m, ['B NUMBER','A NUMBER']].values

Another solution with numpy.where : numpy.where另一个解决方案:

df['B NUMBER'] = np.where(df['A NUMBER'] != 9999574081, df['A NUMBER'], df['B NUMBER'])
df['A NUMBER'] = 9999574081

print (df)
     A NUMBER    B NUMBER
0  9999574081  7042967611
1  9999574081       12320
2  9999574081  9810256463
3  9999574081  9716551924
4  9999574081  9716551924
5  9999574081  8130945859

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM