简体   繁体   English

熊猫:用条件替换列中的值

[英]Pandas: replace values in column with condition

I have dataframe 我有数据框

city_reg     city_live   reg_region    live_region 
 Moscow         Tver        77            69
 Tambov         Tumen'      86            86

I need to replace values in city_reg to values from city_live if reg_region == live_region 我需要替换值city_reg从到值city_live如果reg_region == live_region

I try to use 我尝试使用

df.loc[df.reg_region == df.live_region, 'city_reg'] = df['city_live']

but it returnes 但它返回

ValueError: cannot reindex from a duplicate axis

How can I fix that? 我该如何解决?

Use mask or numpy.where which working with duplicated indices very nice: 使用masknumpy.where可以很好地处理重复索引:

#create duplicated indices for test
df.index = [0,0]
print (df)
  city_reg city_live  reg_region  live_region
0   Moscow      Tver          77           69
0   Tambov    Tumen'          86           86

df['city_reg'] = df['city_reg'].mask(df.reg_region == df.live_region,  df['city_live'])

Or: 要么:

df['city_reg'] = np.where(df.reg_region == df.live_region,  df['city_reg'], df['city_live'])

print (df)
  city_reg city_live  reg_region  live_region
0   Moscow      Tver          77           69
0   Tumen'    Tumen'          86           86

Try this: 尝试这个:

mask = df.reg_region == df.live_region
df.loc[mask, 'city_reg'] = df.loc[mask, 'city_live']

#   city_reg city_live  reg_region  live_region
# 0   Moscow      Tver          77           69
# 1   Tumen'    Tumen'          86           86

The reason this works is that the indices are aligned between the left and right hand sides of the assignment when you apply the same mask. 之所以起作用,是因为当您应用相同的蒙版时,索引在分配的左侧和右侧之间对齐。

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

相关问题 如何用条件 pandas python 替换另一列中的列的值 - how to replace the values of a column from another column with condition pandas python 如何在给定条件的情况下用 pandas dataframe 中的另一列替换一列的值 - How to replace the values of a column with another column in pandas dataframe given a condition 替换满足某些条件的 Pandas 列中的值会导致 SettingWithCopyWarning - Replace values in a pandas column that satisfy some condition leads to SettingWithCopyWarning 根据条件用不同的替换字典替换熊猫数据框列中的值 - Replace values in pandas dataframe column with different replacement dict based on condition Pandas DataFrame:根据条件替换列中的所有值 - Pandas DataFrame: replace all values in a column, based on condition Pandas 数据框根据条件替换列中的值 - Pandas data frame replace values in column based on condition 根据条件,用相应的列名替换 pandas 数据框中的特定值, - Replace specific values in pandas dataframe with the corresponding column name, based on a condition, Pandas:如何根据 ID 和条件替换面板数据集中的列值 - Pandas: How to replace column values in panel dataset based on ID and condition 过滤 pandas dataframe 列并使用列表条件替换值 - Filter pandas dataframe column and replace values using a list condition 熊猫:替换列中的值 - Pandas: replace values in column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM