简体   繁体   English

用单列中的值替换所有列值 - Pandas

[英]Replace all column values with value from single column - Pandas

I'm hoping to replace values in all columns within a df using integers from a specified column.我希望使用指定列中的整数替换df中所有列中的值。 Using the df below I want to use the values in Code and replace them in all other columns.使用下面的df我想使用Code中的值并在所有其他列中替换它们。

df = pd.DataFrame({
    'Place' : ['X','Y','X','Y','X','Y','X','Y'],                                
    'Number' : ['A','B','C','D','F','G','H','I'],          
    'Code' : [1,2,3,0,1,2,5,4],    
    'Value' : ['','','','','','','','']                  
    })

df[:] = df['Code'].apply(lambda x: x if np.isreal(x) else 0).astype(int)

print(df)

Intended Output:预期 Output:

  Place Number  Code Value
0  1     1      1    1     
1  2     2      2    2     
2  3     3      3    3     
3  0     0      0    0     
4  1     1      1    1     
5  2     2      2    2     
6  5     5      5    5     
7  4     4      4    4

Use reindex , ffill , bfill使用reindexffillbfill

df[['Code']].reindex(columns=df.columns).ffill(1).bfill(1).astype(int)

Out[256]:
   Place  Number  Code  Value
0      1       1     1      1
1      2       2     2      2
2      3       3     3      3
3      0       0     0      0
4      1       1     1      1
5      2       2     2      2
6      5       5     5      5
7      4       4     4      4

Numpy solution Numpy解决方案

df[:] =  np.transpose([df.Code] * df.shape[1])

Out[314]:
   Place  Number  Code  Value
0      1       1     1      1
1      2       2     2      2
2      3       3     3      3
3      0       0     0      0
4      1       1     1      1
5      2       2     2      2
6      5       5     5      5
7      4       4     4      4

Try this:尝试这个:

    df[df.columns] = df[['Code', 'Code', 'Code', 'Code']]

or:或者:

    df[df.columns] = df[['Code']*len(df.columns)]

Hope it helps you.希望它可以帮助你。

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

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