gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:25:10 30 4
gpt4 key购买 nike

我有一个示例数据框

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

最佳答案

拆分分解提取更新

我们可以在一个或多个空格字符上拆分Key,前面有:,然后分解 Key 上的数据帧,接下来提取 Key 列中的数字,这些数字前面有 $ 符号并更新 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

关于python - 如何使用 Python 将特定的选定行拆分为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67404140/

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