I am trying to convert a Pandas DF containing sentences into one which shows the number of words in those sentences across all columns and rows.
I have tried apply, transform, lambda functions and nested for loops.
dat.direction.str.split().str.len()
def token_count(x):
if type(x) == str:
return x.split().str.len()
else:
return 0
dat.apply(token_count)
dat.transform(token_count)
dat.apply(lambda x:x.str.split().str.len())
dat.apply(lambda x:x.split().str.len())
dat.transform(lambda x:x.str.split().str.len())
dat.transform(lambda x:x.split().str.len())
dat.iloc[1,3].split(" ").str.len()
AttributeError: 'list' object has no attribute 'str'
How about this
import pandas as pd
df = pd.DataFrame({
"col1": ["this is a sentence", "this is another sentence"],
"col2": ["one more", "this is the last sentence"],
})
pd.concat([df[col].str.split().str.len() for col in df.columns], axis = 1)
stack
stack
to one dimension unstack
back df.stack().str.split().str.len().unstack()
col1 col2
0 4 2
1 4 5
count
instead df.stack().str.count('\s+').unstack() + 1
applymap
df.applymap(lambda s: len(s.split()))
apply
df.apply(lambda s: s.str.split().str.len())
df = pd.DataFrame({
"col1": ["this is a sentence", "this is another sentence"],
"col2": ["one more", "this is the last sentence"],
})
You can iterate over each column in your data frame using your first approach.
out = pd.DataFrame(index=dat.index)
for col in dat:
out[col] = dat[col].str.split().str.len()
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.