Pandas通过列和索引有条件地复制单元格值

时间:2018-05-17 11:45:20

标签: python pandas python-2.6

我想逐行复制单元格。即如果Country是GB,我想将Col2复制到Country FR COL 2.使用pandas

If (Country == "GB") then:
    Copy Col2 from GB to FR COL2

示例

Country Col1   Col2
GB       4       5
FR       2       x
GB       1       6
FR       7       x
GB       2       8
CN       3       x

结果应该是

Country Col1   Col2
GB       4       5
FR       2       5
GB       1       6
FR       7       6
GB       2       8
CN       3       x

2 个答案:

答案 0 :(得分:1)

这是实现结果的一种方法(假设FR

m = df['Country'] == 'FR'
df.loc[m,'Col2'] = df.loc[df['Country'] == 'GB','Col2'].values[:sum(m)]

完整示例:

import pandas as pd

data = '''\
Country Col1   Col2
GB       4       5
FR       2       x
GB       1       6
FR       7       x
GB       2       8
CN       3       x'''

df = pd.read_csv(pd.compat.StringIO(data), sep='\s+')

# Mask
m = df['Country'] == 'FR'

#Assign
df.loc[m,'Col2'] = df.loc[df['Country'] == 'GB','Col2'].values[:sum(m)]

print(df)

返回:

  Country  Col1 Col2
0      GB     4    5
1      FR     2    5
2      GB     1    6
3      FR     7    6
4      GB     2    8
5      CN     3    x

答案 1 :(得分:0)

也许你需要这样的东西:

df.loc[(df['Country'] == 'FR') & (df['Col2'].isnull()) 
      & (df['Country'].shift(1) == 'GB'), 'Col2'] = df['Col2'].shift(1)

或者这个:

df.loc[(df['Country'] == 'FR') 
      & (df['Country'].shift(1) == 'GB'), 'Col2'] = df['Col2'].shift(1)