函数返回 pandas 数据帧
function returning pandas dataframe
我不清楚我的问题,所以我正在审查这个问题。我有一个操作通用数据框的函数(它删除并重命名列和记录):
def manipulate_df(df_local):
df_local.rename(columns={'A': 'grouping_column'}, inplace = True)
df_local.drop('B', axis=1, inplace=True)
df_local.drop(df.query('grouping_column not in (\'1\', \'0\')').index, inplace = True)
df_local = df_local.groupby(['grouping_column'])['C'].sum().to_frame().reset_index().copy()
print("this is what I need:")
print(df_local)
在我的代码主体中调用了这个操作函数:
df = pd.DataFrame(np.random.randint(0,10,size=(100, 3)), columns=list('ABC'))
manipulate_df(df)
print("this is what I got:")
print(df.head(5))
执行前面的块后,这是我得到的输出:
this is what I need:
grouping_column C
0 0 72
1 1 29
this is what I got:
grouping_column C
0 0 5
1 0 5
2 0 4
3 1 9
6 0 5
虽然保留了删除和过滤器,但没有保留分组。
如何实现操作功能以实际对数据帧进行分组?
再次感谢并为我之前的困惑表示歉意post。
问题是,除了不可读的代码,您永远不会 return 更改。
看看这个例子:
a = 'foo'
def my_func(a):
a = 'bar'
my_func(a)
print(a)
#foo
a = my_func(a)
#None
避免所有范围讨论,您需要 return 函数中的某些内容或编辑全局变量:
a = 'foo'
def my_func():
global a
a = 'bar'
myfunc()
print(a)
#bar
或者
一 = 'foo'
def my_func(a):
a = 'bar'
return a
a = myfunc(a)
print(a)
#bar
我不清楚我的问题,所以我正在审查这个问题。我有一个操作通用数据框的函数(它删除并重命名列和记录):
def manipulate_df(df_local):
df_local.rename(columns={'A': 'grouping_column'}, inplace = True)
df_local.drop('B', axis=1, inplace=True)
df_local.drop(df.query('grouping_column not in (\'1\', \'0\')').index, inplace = True)
df_local = df_local.groupby(['grouping_column'])['C'].sum().to_frame().reset_index().copy()
print("this is what I need:")
print(df_local)
在我的代码主体中调用了这个操作函数:
df = pd.DataFrame(np.random.randint(0,10,size=(100, 3)), columns=list('ABC'))
manipulate_df(df)
print("this is what I got:")
print(df.head(5))
执行前面的块后,这是我得到的输出:
this is what I need:
grouping_column C
0 0 72
1 1 29
this is what I got:
grouping_column C
0 0 5
1 0 5
2 0 4
3 1 9
6 0 5
虽然保留了删除和过滤器,但没有保留分组。 如何实现操作功能以实际对数据帧进行分组?
再次感谢并为我之前的困惑表示歉意post。
问题是,除了不可读的代码,您永远不会 return 更改。
看看这个例子:
a = 'foo'
def my_func(a):
a = 'bar'
my_func(a)
print(a)
#foo
a = my_func(a)
#None
避免所有范围讨论,您需要 return 函数中的某些内容或编辑全局变量:
a = 'foo'
def my_func():
global a
a = 'bar'
myfunc()
print(a)
#bar
或者 一 = 'foo'
def my_func(a):
a = 'bar'
return a
a = myfunc(a)
print(a)
#bar