我正在尝试根据另一列的数据替换一列的项目,如下代码:
import pandas as pd
import numpy as np
data = np.array([['3S', 12345],['-2', 12345], ['4S', 12334], ['-2', 12334]])
df = pd.DataFrame(data, columns=['col_1', 'col_2'])
df
#I'd like to find the item "-2" at col_1 and replace it based on the data of the col_2. As result, i'd like to have a dataframe like this:
data = np.array([['3S', 12345],['3S', 12345], ['4S', 12334], ['4S', 12334]])
df = pd.DataFrame(data, columns=['col_1', 'col_2'])
df
答案 0 :(得分:-1)
让我们试试
df.col_1 = df.col_1.mask(df.col_1.isin(['-2'])).\
groupby(df['col_2']).transform('first')
df
Out[50]:
col_1 col_2
0 3S 12345
1 3S 12345
2 4S 12334
3 4S 12334