如何使用 Python 将特定选定行拆分为多行
Posted
技术标签:
【中文标题】如何使用 Python 将特定选定行拆分为多行【英文标题】:How to split a specific selected row to multiple rows using Python 【发布时间】:2021-07-27 22:38:42 【问题描述】:我有一个示例数据框
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)
print(df)
Key Value1 value2
0 First Row 365.0 789.0
1 Sample sample first row: a Row to be splitted $ 369 265.0 NaN
2 Sample second row : a Depreciation $ 458 NaN NaN
3 Last Row 256.0 NaN
我知道使用 Split cell into multiple rows in pandas dataframe 将任何类别拆分为多行
我无法在所选部分拆分一行字符串。
期望的输出
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
【问题讨论】:
【参考方案1】:
split
、explode
、extract
和 update
我们可以split
列Key
上一个或多个space
字符,前面是:
,然后explode
Key
上的数据框,下一个extract
来自@ 的数字987654332@ 列前面有$
符号和update
在Value1
中对应的值
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
【讨论】:
我的朋友很好地使用了正则表达式【参考方案2】:使用 .explode
.str.extract()
和 str.replace()
分 3 步
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
【讨论】:
以上是关于如何使用 Python 将特定选定行拆分为多行的主要内容,如果未能解决你的问题,请参考以下文章