Python 如何获取pandas数据帧中单元格值的长度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37335598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:14:49  来源:igfitidea点击:

How to get the length of a cell value in pandas dataframe?

pythonpandasdataframe

提问by Kevin

Have a pandas dataframe:

有一个熊猫数据框:

idx Event
0   abc/def
1   abc
2   abc/def/hij

Run: df['EventItem'] = df['Event'].str.split("/")

跑: df['EventItem'] = df['Event'].str.split("/")

Got:

得到了:

idx EventItem
0   ['abc','def']
1   ['abc']
2   ['abc','def','hij']

Want to get the length of each cell, run df['EventCount'] = len(df['EventItem'])

想要得到每个的长度cell,运行df['EventCount'] = len(df['EventItem'])

Got:

得到了:

idx EventCount
0   6
1   6
2   6

How can I get the correct count as follow?

我怎样才能得到正确的计数如下?

idx EventCount
0   2
1   1
2   3

回答by root

You can use .str.lento get the length of a list, even though lists aren't strings:

您可以使用.str.len获取列表的长度,即使列表不是字符串:

df['EventCount'] = df['Event'].str.split("/").str.len()

Alternatively, the count you're looking for is just 1 more than the count of "/"'s in the string, so you could add 1 to the result of .str.count:

或者,您要查找的计数仅比"/"字符串中' 的计数多 1 ,因此您可以将 1 添加到 的结果中.str.count

df['EventCount'] = df['Event'].str.count("/") + 1

The resulting output for either method:

任一方法的结果输出:

         Event  EventCount
0      abc/def           2
1          abc           1
2  abc/def/hij           3

Timings on a slightly larger DataFrame:

稍大的 DataFrame 上的计时:

%timeit df['Event'].str.count("/") + 1
100 loops, best of 3: 3.18 ms per loop

%timeit df['Event'].str.split("/").str.len()
100 loops, best of 3: 4.28 ms per loop

%timeit df['Event'].str.split("/").apply(len)
100 loops, best of 3: 4.08 ms per loop

回答by johnchase

You can use applyto apply the lenfunction to each column:

您可以使用applylen函数应用于每一列:

df['EventItem'].apply(len)

0    2
1    1
2    3
Name: EventItem, dtype: int64