【发布时间】:2019-08-25 19:09:36
【问题描述】:
我有一个数据框
df = pd.DataFrame({'col1': [1,2,1,2], 'col2': ['aa bb cc', 'ee-ff-gg', 'hh ii kk', 'll-mm-nn']})
我想:
- 在 col1==1 的“”上拆分 col2
- 在 col1==2 的“-”上拆分
- 将此数据附加到 3 个新列:(col20, col21, col22)
理想情况下,代码应如下所示:
subdf=df.loc[df['col1']==1]
#list of columns to use
col_list=['col20', 'col21', 'col22']
#append to dataframe new columns from split function
subdf[col_list]=(subdf.col2.str.split(' ', 2, expand=True)
然而这并没有奏效。
我尝试过使用 merge 和 join,但是:
- 如果列已填充,则连接不起作用
- 如果不这样做,合并将不起作用。
我也试过了:
#subset dataframes
subdf=df.loc[df['col1']==1]
subdf2=df.loc[df['col1']==2]
#trying the join method, only works if columns aren't already present
subdf.join(subdf.col2.str.split(' ', 2, expand=True).rename(columns={0:'col20', 1:'col21', 2: 'col22'}))
#merge doesn't work if columns aren't present
subdf2=subdf2.merge(subdf2.col2.str.split('-', 2, expand=True).rename(columns={0:'col20', 1:'col21', 2: 'col22'}))
subdf2
运行时的错误信息:
subdf2=subdf2.merge(subdf2.col2.str.split('-', 2, expand=True).rename(columns={0:'col20', 1:'col21', 2: 'col22'})
MergeError: No common columns to perform merge on. Merge options: left_on=None, right_on=None, left_index=False, right_index=False
在标记对正则表达式的评论后编辑给出信息
我原来的 col1 实际上是我用来从一些字符串中提取 col2 的正则表达式组合。
#the combination I used to extract the col2
combinations= ['(\d+)[-](\d+)[-](\d+)[-](\d+)', '(\d+)[-](\d+)[-](\d+)'... ]
这是原始数据框
col1 col2
(\d+)[-](\d+)[-](\d+)[-](\d+) 350-300-50-10
(\d+)[-](\d+)[-](\w+)(\d+) 150-180-G31
然后我创建了一个字典,将每个组合与 col2 的拆分值表示的内容联系起来:
filtermap={'(\d+)[-](\d+)[-](\w+)(\d+)': 'thickness temperature sample', '(\d+)[-](\d+)[-](\d+)[-](\d+)': 'thickness temperature width height' }
我想用这个过滤器:
- 根据正则表达式组合对数据帧进行子集
- 在 col2 上使用 split 以使用 filtermap(厚度温度..)查找与组合对应的值
- 将这些值添加到数据框的新列中
col1 col2 thickness temperature width length sample
(\d+)[-](\d+)[-](\d+)[-](\d+) 350-300-50-10 350 300 50 10
(\d+)[-](\d+)[-](\w+)(\d+) 150-180-G31 150 180 G31
既然您提到了正则表达式,也许您知道一种直接执行此操作的方法?
编辑 2;输入输出
在输入中有这样的字符串:
'this is the first example string 350-300-50-10 ',
'this is the second example string 150-180-G31'
以下格式:
-
number-number-number-number(350-300-50-10) 里面有这个有序的信息:thickness(350)-temperature(300)-width(50)-length(10)
-
number-number-letternumber (150-180-G31 ) 中有这个有序的信息:thickness-temperature-sample
想要的输出:
col2, thickness, temperature, width, length, sample
350-300-50-10 350 300 50 10 None
150-180-G31 150 180 None None G31
我用过例如:
re.search('(\d+)[-](\d+)[-](\d+)[-](\d+)'))
在字符串中查找 col2
【问题讨论】:
-
rsplit可能会起作用。 pandas.pydata.org/pandas-docs/stable/reference/api/… -
拆分有效,但我无法创建填充拆分结果的 3 个新列。子集给了我主要问题。
标签: python pandas dataframe split