将Pandas DataFrame列分解为唯一值Python的字符串



i具有一个数据框

数据框列看起来像:

[In]: df
[Out]:
 0   -- Generated 
 1   -- Formatting      
 2   -- Project1     
 3   -- Help        
 4   GRI                               -- Gen     
 5   S-P                               -- Gen
 6   COORD-SYS                         -- Gen
 7   COORD                             -- Gen
 8     318108.6945 6146696.895 1829.01714 318108.6945 6146696.895 
 9     1917.90444 334108.6945 6146696.895 1610.670059 334108.6945 
 10    6146696.895 1713.102355 350108.6945 6146696.895 1417.752346 350108.6945 
 11    NEF                             -- Gen
 12    318108.6945 6146696.895 1829.01714 318108.6945 6146696.895 
       2025.480832 326108.6945 6146696.895 1716.342492 326108.6945
 13    1917.90444 334108.6945 6146696.895 1610.670059 334108.6945 
       6146696.895 1813.845155 342108.6945 342108.6945
.
.

我想通过不是数字的字符串将此列数据框架分开,并将其下面的所有数值取直到出现下一个非数值值。

我需要的输出(例如,对于坐标,NEF的类似(看起来像这样:

[In]: df_COORD 
[Out]:

 0     COORD       1            2           3           4            5         
 1     318108.6945 6146696.895  1829.01714  318108.6945 6146696.895  nan
 2     1917.90444  334108.6945  6146696.895 1610.670059 334108.6945  nan
 3     6146696.895 1713.102355  350108.6945 6146696.895 1417.752346 350108.6945 

我首先尝试使用:

df_COORD = pd.DataFrame(df[0][7:11]).reset_index(drop=True)
df_COORD= df_COORD.rename(columns=df_COORD.iloc[0]).drop(0)
df_COORD= df_COORD[file_coord.iloc[0][0]].str.split(expand=True)

哪个有效,但我不必明确说明我想要哪一行;我想基于包含 COORDNEF的列值或唯一字符串的任何其他list分开,然后在下面获取数据,直到到达另一个字母的字符串。

我有什么办法可以做到吗?

从我的理解中,您需要的是标记相关行的块,然后使用GroupBy创建单独的数据帧。根据您的描述,新的DF应从包含非数字的行开始。假设您的Origin DF具有默认名称0

的此列
# flag the block based on the regex and cumsum()
# Warning: you might also consider scientific notation of numbers in regex
g1 = (df[0].str.contains('[^d.s+-]')).cumsum()
# initialize the dict for all sub-dataframes
dfs = {}
for g, d in df.groupby(g1):
    # having only 1 row in the sub-dataframue, then they are unrelated and skipped
    if d[0].size == 1: continue
    # do whatever you want to groups with rows containing numbers
    d = d[0].str.strip(' t').str.split(expand=True)
    dname = d[0].iat[0]
    dfs[dname] = d.iloc[1:,:].rename(columns={0:dname})
    print(dfs[dname])

最新更新