使用动态名称在 Pandas 中创建新数据框还会添加新列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40973687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create new dataframe in pandas with dynamic names also add new column
提问by user07
I have a dataframe df
我有一个数据框 df
df = pd.DataFrame({'A':['-a',1,'a'],
'B':['a',np.nan,'c'],
'ID':[1,2,2],
't':[pd.tslib.Timestamp.now(),pd.tslib.Timestamp.now(),
np.nan]})
Added a new column
添加了一个新列
df['YearMonth'] = df['t'].map(lambda x: 100*x.year + x.month)
Now I want to write a function or macro which will do date comparasion, create a new dataframe also add a new column to dataframe.
现在我想编写一个函数或宏来进行日期比较,创建一个新的数据框并向数据框添加一个新列。
I tried like this but seems I am going wrong:
我试过这样,但似乎我错了:
def test(df,ym):
df_new=df
if(ym <= df['YearMonth']):
df_new+"_"+ym=df_new
return df_new+"_"+ym
df_new+"_"+ym['new_col']=ym
Now when I call test function I want a new dataframe should get created named as df_new_201612
and this new dataframe should have one more column, named as new_col
that has value of ym
for all the rows.
现在,当我调用测试函数时,我希望创建一个名为 as 的df_new_201612
新数据框,并且这个新数据框应该多有一列,命名为所有行的new_col
值为ym
。
test(df,201612)
The output of new dataframe is:
新数据帧的输出是:
df_new_201612
df_new_201612
A B ID t YearMonth new_col
-a a 1 2016-12-05 12:37:56.374620 201612 201612
1 NaN 2 2016-12-05 12:37:56.374644 201208 201612
a c 2 nat nan 201612
回答by FLab
Creating variables with dynamic names is typically a bad practice.
创建具有动态名称的变量通常是一种不好的做法。
I think the best solution for your problem is to store your dataframes into a dictionary and dynamically generate the name of the key to access each dataframe.
我认为解决您的问题的最佳解决方案是将您的数据帧存储到字典中,并动态生成访问每个数据帧的键名。
import copy
dict_of_df = {}
for ym in [201511, 201612, 201710]:
key_name = 'df_new_'+str(ym)
dict_of_df[key_name] = copy.deepcopy(df)
to_change = df['YearMonth']< ym
dict_of_df[key_name].loc[to_change, 'new_col'] = ym
dict_of_df.keys()
Out[36]: ['df_new_201710', 'df_new_201612', 'df_new_201511']
dict_of_df
Out[37]:
{'df_new_201511': A B ID t YearMonth new_col
0 -a a 1 2016-12-05 07:53:35.943 201612 201612
1 1 NaN 2 2016-12-05 07:53:35.943 201612 201612
2 a c 2 2016-12-05 07:53:35.943 201612 201612,
'df_new_201612': A B ID t YearMonth new_col
0 -a a 1 2016-12-05 07:53:35.943 201612 201612
1 1 NaN 2 2016-12-05 07:53:35.943 201612 201612
2 a c 2 2016-12-05 07:53:35.943 201612 201612,
'df_new_201710': A B ID t YearMonth new_col
0 -a a 1 2016-12-05 07:53:35.943 201612 201710
1 1 NaN 2 2016-12-05 07:53:35.943 201612 201710
2 a c 2 2016-12-05 07:53:35.943 201612 201710}
# Extract a single dataframe
df_2015 = dict_of_df['df_new_201511']