我是熊猫和数据框架的新手,所以我希望这不是一个太基本的问题。
假设我(外部)合并了两个数据帧并获得了以下内容:
date_a symbol_a value_a type_a symbol_b date_b value_b type_b total
0 yymmdd AAAA 10 W AAAA yymmdd 2 S 12
1 yymmdd BBBB 5 W BBBB yymmdd 2 S 7
2 yymmdd CCCC 12 W NaN NaN NaN NaN NaN
3 yymmdd DDDD 15 W NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN EEEE yymmdd 5 S NaN
5 NaN NaN NaN NaN FFFF yymmdd 10 S NaN
6 NaN NaN NaN NaN GGGG yymmdd 2 S NaN
到目前为止,这是我想要的(日期都是同一天)。
现在假设我有一条规则告诉我我有一个映射(字典):
mapper = {'EEEE':'CCCC', 'FFFF':'DDDD'}
我的symbol_b可能没有映射到任何symbol_a(如上面的索引6)。
我的问题是,是否可以根据字典给出的映射重新排列行,以便得到:
date_a symbol_a value_a type_a symbol_b date_b value_b type_b total
0 yymmdd AAAA 10 W AAAA yymmdd 2 S 12
1 yymmdd BBBB 5 W BBBB yymmdd 2 S 7
2 yymmdd CCCC 12 W EEEE yymmdd 5 S 17
3 yymmdd DDDD 15 W FFFF yymmdd 10 S 25
6 NaN NaN NaN NaN GGGG yymmdd 2 S NaN
理想情况下,我还要删除包含NaN元素的所有行,以便最终结果为:
date_a symbol_a value_a type_a symbol_b date_b value_b type_b total
0 yymmdd AAAA 10 W AAAA yymmdd 2 S 12
1 yymmdd BBBB 5 W BBBB yymmdd 2 S 7
2 yymmdd CCCC 12 W EEEE yymmdd 5 S 17
3 yymmdd DDDD 15 W FFFF yymmdd 10 S 25
答案 0 :(得分:1)
因此,我将您的数据框拆分为原始的2个数据框,只需更改数据框中的列名称即可符合您的使用情况:
import pandas as pd
a = pd.read_csv('test.csv')
#Split your merge df into 2 original df
del a['total']
df1 = a.loc[:, ['date_a', 'symbol_a', 'value_a', 'type_a']]
df2 = a.loc[:, ['date_b', 'symbol_b', 'value_b', 'type_b']]
df1.fillna('', inplace=True)
df2.fillna('', inplace=True)
df1 = df1[df1['date_a']!='']
df2 = df2[df2['date_b']!='']
#Add a mapping column to df2
mapper = {'EEEE':'CCCC', 'FFFF':'DDDD'}
df2['mapping'] = df2['symbol_b'].apply(lambda x: mapper.get(x) if mapper.get(x)!= None else x)
df1 = df1.merge(df2, left_on='symbol_a', right_on='mapping')
df1['total'] = df1['value_a'] + df1['value_b']
df1
df1中的结果现在是:
date_a symbol_a value_a type_a date_b symbol_b value_b type_b mapping total
0 yymmdd AAAA 10.0 W yymmdd AAAA 2.0 S AAAA 12.0
1 yymmdd BBBB 5.0 W yymmdd BBBB 2.0 S BBBB 7.0
2 yymmdd CCCC 12.0 W yymmdd EEEE 5.0 S CCCC 17.0
3 yymmdd DDDD 15.0 W yymmdd FFFF 10.0 S DDDD 25.0