如何在 Python pandas DataFrame 中对列值进行切片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48773767/
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-09-14 05:10:26 来源:igfitidea点击:
How to slice column values in Python pandas DataFrame
提问by dsk
I have a dataframe like this-
我有一个这样的数据框-
element id year month days tmax tmin
0 MX17004 2010 1 d1 NaN NaN
1 MX17004 2010 1 d10 NaN NaN
2 MX17004 2010 1 d11 NaN NaN
3 MX17004 2010 1 d12 NaN NaN
4 MX17004 2010 1 d13 NaN NaN
where I want to further break days column like this **
我想进一步打破这样的日子专栏**
days
1
10
11
12
13
** I have tried a couple of ways, but not successful in getting the output. Can someone please help or some clue?
** 我尝试了几种方法,但没有成功获得输出。有人可以帮忙或提供一些线索吗?
回答by YOBEN_S
By using str
slice
通过使用str
切片
df.days=df.days.str[1:]
df
Out[759]:
element id year month days tmax tmin
0 0 MX17004 2010 1 1 NaN NaN
1 1 MX17004 2010 1 10 NaN NaN
2 2 MX17004 2010 1 11 NaN NaN
3 3 MX17004 2010 1 12 NaN NaN
4 4 MX17004 2010 1 13 NaN NaN
回答by Scott Boston
Use extract
with regex:
extract
与正则表达式一起使用:
df['days'] = df.days.str.extract('d(\d+)', expand=False)
print(df)
Output:
输出:
element id year month days tmax tmin
0 0 MX17004 2010 1 1 NaN NaN
1 1 MX17004 2010 1 10 NaN NaN
2 2 MX17004 2010 1 11 NaN NaN
3 3 MX17004 2010 1 12 NaN NaN
4 4 MX17004 2010 1 13 NaN NaN