假设我有一个如下数据框:
import pandas as pd
df1 = pd.DataFrame({
'A' : ['foo ', 'b,ar', 'fo...o', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],
})
我想创建一个新数据框,df2
,它是df1
中“ A”和“ B”列的串联形式,其中每个数据都大写。这是一个玩具示例,在我的用例中,我可能还拥有比列“ A”和“ B”更多的列,因此我想使列的列表可变(即列名)。列可能会有所不同)。
def tokenize(s):
# replaces comma with space; removes non-alphanumeric chars; etc.
return re.sub('[^0-9a-zA-Z\s]+', '', re.sub('[,]+', ' ', s)).lower().split()
df2 = pd.DataFrame() # create a new dataframe; not sure if I'm doing this right
cols_to_concat = ['A','B'] # there can be more than two columns in this list
for col in cols_to_concat:
df2 = df1[col].apply(tokenize).apply(str.upper)
print(df2)
# here, I'd like the df2 to have just ONE column whose rows are 'FOOONE', 'BARONE', 'FOOTWO', 'BARTHREE','FOOTWO', 'BARTWO','FOOONE','FOOTHREE',...
答案 0 :(得分:2)
list_o_cols = ['A', 'B']
df1[list_o_cols].sum(1).str.upper()
0 FOOONE
1 BARONE
2 FOOTWO
3 BARTHREE
4 FOOTWO
5 BARTWO
6 FOOONE
7 FOOTHREE
dtype: object
df2 = df1[list_o_cols].sum(1).str.upper().str.replace('O', '').to_frame('col_name')
df2
col_name
0 FNE
1 BARNE
2 FTW
3 BARTHREE
4 FTW
5 BARTW
6 FNE
7 FTHREE
答案 1 :(得分:1)
ConcatCol = ['A', 'B']
df2 = pd.DataFrame(df1[ConcatCol].apply(lambda x: ''.join(x.str.upper()), axis=1), columns=['Col'])
根据您的评论,您可以在lambda函数之后应用函数,如果要进行串联然后应用函数:
# your function
def tokenize(s):
# replaces comma with space; removes non-alphanumeric chars; etc.
return re.sub('[^0-9a-zA-Z\s]+', '', re.sub('[,]+', ' ', s)).lower().split()
ConcatCol = ['A', 'B']
df2 = pd.DataFrame(df1[ConcatCol].apply(lambda x: ''.join(x), axis=1).apply(tokenize), columns=['Col'])
Col
0 [foo, one]
1 [b, arone]
2 [footwo]
3 [barthree]
4 [footwo]
5 [bartwo]
6 [fooone]
7 [foothree]
要先应用您的函数,然后再使用concat,答案会稍有不同,因为您的函数使用split
创建列表。因此,最终,您将使用sum将列表组合在一起:
def tokenize(s):
# replaces comma with space; removes non-alphanumeric chars; etc.
return re.sub('[^0-9a-zA-Z\s]+', '', re.sub('[,]+', ' ', s)).lower().split()
ConcatCol = ['A', 'B']
df2 = pd.DataFrame(df1[ConcatCol].apply(lambda x: (x.apply(tokenize))).sum(axis=1), columns=['Col'])
Col
0 [foo, one]
1 [b, ar, one]
2 [foo, two]
3 [bar, three]
4 [foo, two]
5 [bar, two]
6 [foo, one]
7 [foo, three]