我想逐行复制单元格。即如果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
答案 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)