Suppose I have a dataframe like below:
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'],
})
I want to create a new dataframe , df2
, that is a concatenated form of column 'A' and 'B' in df1
where each data is uppercased. This is a toy example, and in my use case, I may also have more than the column 'A' and 'B', so I'd like to make the list of columns variable (that is, the names of the column can vary) .
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',...
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
ConcatCol = ['A', 'B']
df2 = pd.DataFrame(df1[ConcatCol].apply(lambda x: ''.join(x.str.upper()), axis=1), columns=['Col'])
Based on your comment you can just apply your function after the lambda function if you want to concatenate and then apply your function:
# 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]
To apply your function first and then concat will have a slightly different answer because your function uses split
to create lists. So, ultimately, you are just going to combine the list together using 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.