从循环中的字符串列表创建新的列名 [英] Creating new column names from a list of strings in a loop
本文介绍了从循环中的字符串列表创建新的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我在熊猫中有以下列名: ["A","B"]
Let us say I have the following column names in pandas: ["A", "B"]
我的问题是我想使用一个for循环,该循环从列表中获取列名,并创建一个新的列名,其中包括列表中那些元素的一部分.
My problem is that I want to use a for loop that grabs the column names from the list and creates a new column name that includes part of those elements from the list.
在每次迭代中,我想创建以下内容:
In each iteration I would like to create the following:
a = ["A", "B"]
for elements i in a:
elements + "_c" = SOME FUNCTION column <df.elements>
这将导致添加两个新列,名称分别为A_c和B_c.
That should result in the addition of two new columns with names A_c and B_c.
推荐答案
You can use Series.apply
in loop:
a = ["A", "B"]
for i in a:
df[i + "_c"] = df[i].apply(SOME FUNCTION)
或 DataFrame.apply
与对于新的df
add_suffix
然后 join
还原为原始内容:
Or DataFrame.apply
with add_suffix
for new df
and then join
to original:
df1 = df[a].apply(SOME FUNCTION).add_suffix('_c')
df = df.join(df1)
示例:
df = pd.DataFrame({'A':[4,5,4,5,5,4],
'B':[7,8,9,4,2,3],
'C':[1,3,5,7,1,0]})
print (df)
A B C
0 4 7 1
1 5 8 3
2 4 9 5
3 5 4 7
4 5 2 1
5 4 3 0
def FUNCTION(x):
return x + 10
a = ["A", "B"]
for i in a:
df[i + "_c"] = df[i].apply(FUNCTION)
print (df)
A B C A_c B_c
0 4 7 1 14 17
1 5 8 3 15 18
2 4 9 5 14 19
3 5 4 7 15 14
4 5 2 1 15 12
5 4 3 0 14 13
df = df.join(df[a].apply(FUNCTION).add_suffix('_c'))
print (df)
A B C A_c B_c
0 4 7 1 14 17
1 5 8 3 15 18
2 4 9 5 14 19
3 5 4 7 15 14
4 5 2 1 15 12
5 4 3 0 14 13
这篇关于从循环中的字符串列表创建新的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文