gpt4 book ai didi

python - 从 Pandas DataFrame 中的字符串中提取最小和最大年份

转载 作者:行者123 更新时间:2023-12-01 02:40:56 25 4
gpt4 key购买 nike

我有一个 CSV 文件,我将其读入 Pandas DataFrame,其中包含一列,其中包含用分号分隔的多个年份值。

我需要从字符串中提取最小值和最大值并将每个值保存在新列中。

我可以打印最小值和最大值,但我似乎无法从保存到新列中的每一行中获取正确的值。

非常感谢任何帮助。

示例数据框:

import pandas as pd
import numpy as np

raw_data = {'id': ['1473-2262', '2327-9214', '1949-8349', '2375-6314',
'0095-6562'],
'years': ['2000; 2001; 2002; 2003; 2004; 2004; 2004; 2005',
'2003; 2004; 2005', '2015', np.nan, '2012; 2014']}
df = pd.DataFrame(raw_data, columns = ['id', 'years'])

这是我需要的数据框:

          id                                           years  minyear  maxyear
0 1473-2262 2000; 2001; 2002; 2003; 2004; 2004; 2004; 2005 2000.0 2005.0
1 2327-9214 2003; 2004; 2005 2003.0 2005.0
2 1949-8349 2015 2015.0 2015.0
3 2375-6314 NaN NaN NaN
4 0095-6562 2012; 2014 2012.0 2014.0

我可以打印最小值和最大值:

x = df['years'].notnull()

for row in df['years'][x].str.split(pat=';'):
lst = list()
for item in row:
lst.append(int(item))
print('Min=',min(lst),'Max=',max(lst))

Min= 2000 Max= 2005
Min= 2003 Max= 2005
Min= 2015 Max= 2015
Min= 2012 Max= 2014

以下是我尝试将值捕获到新列的方法:

x = df['years'].notnull()

for row in df['years'][x].str.split(pat=';'):
lst = list()
for item in row:
lst.append(int(item))
df['minyear']=min(lst)
df['maxyear']=max(lst)

仅最后一行的值会保存到新列中。

              id                                           years  minyear  maxyear
0 1473-2262 2000; 2001; 2002; 2003; 2004; 2004; 2004; 2005 2012 2014
1 2327-9214 2003; 2004; 2005 2012 2014
2 1949-8349 2015 2012 2014
3 2375-6314 NaN 2012 2014
4 0095-6562 2012; 2014 2012 2014

最佳答案

我认为你需要str.split使用 expand=True 获取新的 DataFrame,然后转换为 float

索引值相同,因此分配新列:

df1 = df['years'].str.split('; ', expand=True).astype(float)
df = df.assign(maxyear=df1.max(axis=1),minyear=df1.min(axis=1))
#same as
#df['maxyear'], df['minyear'] = df1.min(axis=1), df1.max(axis=1)
print (df)
id years maxyear minyear
0 1473-2262 2000; 2001; 2002; 2003; 2004; 2004; 2004; 2005 2000.0 2005.0
1 2327-9214 2003; 2004; 2005 2003.0 2005.0
2 1949-8349 2015 2015.0 2015.0
3 2375-6314 NaN NaN NaN
4 0095-6562 2012; 2014 2012.0 2014.0

关于python - 从 Pandas DataFrame 中的字符串中提取最小和最大年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45720093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com