Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python将特定选定行拆分为多行_Python_Regex_Pandas_Dataframe_Extract - Fatal编程技术网

如何使用Python将特定选定行拆分为多行

如何使用Python将特定选定行拆分为多行,python,regex,pandas,dataframe,extract,Python,Regex,Pandas,Dataframe,Extract,我有一个示例数据帧 import pandas as pd import numpy as np data = {"Key" : ["First Row", "Sample sample first row: a Row to be splitted $ 369", "Sample second row : a Depreciation $ 458", "Last Row"],

我有一个示例数据帧

import pandas as pd
import numpy as np

data = {"Key" : ["First Row", "Sample sample first row: a Row to be splitted $ 369", "Sample second row : a Depreciation $ 458", "Last Row"],
        "Value1" : [365, 265.0, np.nan, 256],
        "value2" : [789, np.nan, np.nan, np.nan]
}


df = pd.DataFrame(data)
我知道使用

我找不到在所选部分拆分一行字符串

所需输出

              Key                  Value1   value2
0        First Row                  365.0    789.0
1   Sample sample first row:        265.0     NaN
2   a Row to be splitted $            369     NaN
3   Sample second row :               NaN     NaN
4   Depreciation $                    458     NaN
5    Last Row                       256.0     NaN

使用
.explode
.str.extract()和
str.replace()


拆分
分解
提取
更新
我们可以在一个或多个
空格
字符上
拆分
列,该字符前面有
,然后
分解
上的数据框,接下来
列中提取前面带有
$
符号的数字,并
更新
值1

df1 = df.assign(Key=df['Key'].str.split(r'(?<=:)\s+')).explode('Key')
df1['Value1'].update(df1['Key'].str.extract(r'\$\s*(\d+)', expand=False).astype(float))

很好地使用了regex,我的朋友
df1 = df.assign(Key=df['Key'].str.split(':')).explode('Key')

df1['Value1'] = df1['Value1'].fillna(
                      df1['Key'].str.extract('\$\s(\d+)').astype(float)[0]
                                  )
df1['Key'] = df1['Key'].str.replace('(\$\s)(\d+)',r'\1',regex=True)
                        Key  Value1  value2
0                 First Row   365.0   789.0
1   Sample sample first row   265.0     NaN
1   a Row to be splitted $    265.0     NaN
2        Sample second row      NaN     NaN
2         a Depreciation $    458.0     NaN
3                  Last Row   256.0     NaN
df1 = df.assign(Key=df['Key'].str.split(r'(?<=:)\s+')).explode('Key')
df1['Value1'].update(df1['Key'].str.extract(r'\$\s*(\d+)', expand=False).astype(float))
>>> df1
                          Key  Value1  value2
0                   First Row   365.0   789.0
1    Sample sample first row:   265.0     NaN
1  a Row to be splitted $ 369   369.0     NaN
2         Sample second row :     NaN     NaN
2        a Depreciation $ 458   458.0     NaN
3                    Last Row   256.0     NaN