[英]How to “rearrange” a pandas data-frame using a map between columns?
I'm new to pandas and data-frames so I hope this is not a too basic question. 我是熊猫和数据框架的新手,所以我希望这不是一个太基本的问题。
Suppose I have (outer) merged two data frames and obtained the following: 假设我(外部)合并了两个数据帧并获得了以下内容:
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
this is so far quite what I want (the dates are all the same day). 到目前为止,这正是我想要的(日期都是同一天)。
Now suppose I have a rule that tells me that I have a mapping (dictionary): 现在,假设我有一条规则告诉我我有一个映射(字典):
mapper = {'EEEE':'CCCC', 'FFFF':'DDDD'}
I may have symbol_b that are not mapped to any symbol_a (like index 6 above). 我可能有没有映射到任何symbol_a的symbol_b(如上面的索引6)。
My question is, is it possible to use re-arrange the rows according to the mapping given by the dictionary so to get: 我的问题是,是否有可能根据字典给出的映射使用重新排列行,以便获得:
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
Ideally then I would also like to get rid of all the rows that contain a NaN element, so that the final result would be: 理想情况下,我还要摆脱包含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
So, I split your dataframe to the original 2 dataframes, just change the name of columns in dataframe to fit your usage: 因此,我将您的数据框拆分为原始的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
The results in df1 is now: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.