如何在python中从df.apply调用中获取列名?
难题:我需要将df.apply与来自的一行数据一起使用 df,但我不知道返回列的名称 调用df.apply的时间,列名取决于 df.apply的行输入 关于pd.concat还有一些其他的stackoverflow讨论 和result_type='expand',但它们并不完全符合我的目的 请回答一个简单的,尽可能少的行应用策略如何在python中从df.apply调用中获取列名?,python,dataframe,Python,Dataframe,难题:我需要将df.apply与来自的一行数据一起使用 df,但我不知道返回列的名称 调用df.apply的时间,列名取决于 df.apply的行输入 关于pd.concat还有一些其他的stackoverflow讨论 和result_type='expand',但它们并不完全符合我的目的 请回答一个简单的,尽可能少的行应用策略 import pandas as pd def my_func(x): # get_dictionary call will return a consis
import pandas as pd
def my_func(x):
# get_dictionary call will return a consistent number of key/values pairs
# with the keys being consistent each call.
# e.g. {'key1': [5], 'key2': [5.6]}
dict_of_vals = get_dictionary(x.name, x.some_other_value)
# create a Series with the values - ONE row # can't name columns here??
return pd.Series( list(dict_of_vals.values()) )
# assume df is init with some number of columns/rows,
# see below for example
df = init()
# I need the keys from the my_func call e.g. dict_of_vals.keys()
# for the column names here
df[DONT_KNOW_KEYS_UNTIL_CALL_TO_MY_FUNC] = df.apply(lambda x: my_func(x), axis=1)
# assume initial table from init call above
numbers colors
0 1 red
1 2 white
2 3 blue
# want solution to look something like this:
numbers colors key1 key2
0 1 red 5 5.6
1 2 white 6 7.7
2 3 blue 7 8.8
Again, I won't know the column names and values until the apply
calls my_func.
example, if
dict_of_vals = {'key1': [5], 'key2': [5.6]}
I get
key1 key2
0 [5] [5.6]
1 [5] [5.6]
2 [5] [5.6]
which is missing the original columns
我建议使用Pandas的append函数
df.append(df.apply(lambda x: my_func(x), axis=1))
通过这种方式,可以附加未知列的数据框,并获得原始列和新列的组合数据框您可以命名熊猫系列的索引,它们将成为df.apply创建的数据框中的列名 然后,您可以将新创建的数据帧与原始数据帧连接或附加
将熊猫作为pd导入
df1=pd.DataFrame(范围(5),列=['Numbers'])
数字
0 0
1 1
2 2
3 3
4 4
定义我的函数(x):
数字=x[“数字”]
返回pd.Series([number*2,number*3],索引=['Times2','Times3']))
df2=df1.apply(λx:my_func(x),轴=1)
时间2时间3
0 0 0
1 2 3
2 4 6
3 6 9
4 8 12
df_final=df1.join(df2)
次数2次3次
0 0 0 0
1 1 2 3
2 2 4 6
3 3 6 9
4 4 8 12