[英]pandas groupby column values and replace grouped values in another column
我有一个这样的数据框:
股票代码 | 仪器名称 | 年 | 月 | 仪器类型 | 到期类型 |
---|---|---|---|---|---|
ABAN10SEPFUT | 阿班 | 10 | 九月 | FUT | 钠 |
ABAN10OCTFUT | 阿班 | 10 | 华侨城 | FUT | 钠 |
ABAN10NOVFUT | 阿班 | 10 | 十一月 | FUT | 钠 |
我想按instrument_type ('FUT') 分组并在month中找到唯一值。 然后将唯一值与月份列进行比较,并在expiry_type列中将值替换为“I”、“II”、“III”。
预期结果:
股票代码 | 仪器名称 | 年 | 月 | 仪器类型 | 到期类型 |
---|---|---|---|---|---|
ABAN10SEPFUT | 阿班 | 10 | 九月 | FUT | 我 |
ABAN10OCTFUT | 阿班 | 10 | 华侨城 | FUT | 二 |
ABAN10NOVFUT | 阿班 | 10 | 十一月 | FUT | 三 |
我的代码看起来像 #1
def condition(x):
if x =='SEP':
return "I"
elif x =='OCT':
return "II"
elif x =='NOV':
return "III"
else:
return ''
#2
for index, row in path.iterrows():
data = pd.read_parquet(row['location'])
data['expiry_type'] = np.where((data['instrument_type'] == 'FUT'),data['month'].apply(condition),'')
由于我已经知道月份列中的唯一值,所以我创建了一个自定义函数来替换 expiry_type 列中的值。 我有类似的文件,所以有没有办法找到唯一值并自动替换。 我怎么做? 先感谢您!
考虑到您已按instrument_type
分组,您可以构建一个类似于 #1 中的函数:
def condition(x):
if x.month =='SEP':
return "I"
elif x.month =='OCT':
return "II"
elif x.month =='NOV':
return "III"
else:
return ''
并将此函数应用于expiry_type
列:
df['expiry_type'] = df.apply(condition, axis = 1).
您可以使用 Pandas唯一函数在列中查找唯一值。 对您拥有的每个 DataFrame 使用 for 循环,在month
列上应用unique
函数以获得唯一值列表。 然后,使用这些值作为键和新的表示形式(在这个特定示例中为罗马数字)作为值来创建一个字典。 然后,您可以使用map函数替换month
列中的值并将新值分配给expiry_type
列。
def toRoman(n):
roman = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII']
return roman[n]
df_list = ['df1.csv', 'df2.csv', 'df3.csv']
for df_file in df_list:
df = pd.read_csv(df_file)
g = df.groupby('instrument_type')
uniq = g['month'].unique()[0]
# create a dictionary using the unique values
dict_map = {name:toRoman(idx) for idx,name in enumerate(uniq)}
df['expiry_type'] = df['month'].map(dict_map)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.