【问题标题】:How to parse/manipulate string values in python?如何在python中解析/操作字符串值?
【发布时间】:2021-02-24 05:03:41
【问题描述】:

我有一个这样的 csv 数据集 -

TABLE NAME IS A VERSION IS 1
TYPE IS CODE
TABLE IS UNSORTED
VALUES ARE ( 01 P 02 N 03 S 04 A )
SEARCH IS LINEAR
,
TABLE NAME IS B VERSION IS 1
TYPE IS CODE
TABLE IS SORTED
VALUES ARE ( 0A M 0B S 0A D 01 ' ' 04 N 05 P 07 T 08 K 09 E )
SEARCH IS LINEAR

我做了一些解析。代码如下:

df_type_code = df[df["Type"]=="CODE"]
columns = ['Table Name', 'Value']
df_type_code = pd.DataFrame(df_type_code, columns=columns)

for index, row in df_type_code.iterrows():
    span = 2
    words = row.Value.split(" ")
    row.Value = [",".join(words[i:i+span]) for i in range(0, len(words), span)]
df_type_code['Index'] = df_type_code.index

df_temp = (pd.DataFrame({'Table Name': list(df_type_code['Table Name']),
                    'Value': list(df_type_code['Value']),
                       'Index': list(df_type_code['Index'])})
      .set_index(['Index', 'Table Name']))

temp = df_temp.explode('Value')
temp.reset_index(inplace=True, level=1)
df_new = temp[['Table Name', 'Value']]

df_final = pd.concat([df_new, df_new['Value'].str.split(',', expand=True)], axis=1)
df_final = df_final.drop(df_final.columns[[1]], axis=1)
df_final.columns = ['Table Name', '1st', '2nd']
df_final.reset_index(inplace=True)
df_final = df_final[['Table Name', '1st', '2nd']]
print(df_final)

所以最终输出如下:

基本上我想要实现的是,在值中,第一项和第二项是链接的,所以它们应该排成一行。

现在我在数据集中得到了一个新的数据项如下:

TABLE NAME IS C VERSION IS 1
TYPE IS CODE
TABLE IS SORTED
VALUES ARE ( A '02 01' B '04 26' F '08 13' H '07 24' M '02 12' Q '06 04' S '08 02' )
SEARCH IS NONLINEAR

上面的代码将 A 和 '02 放在一行中, 01' 和 B 在第二行中,依此类推。 在这种情况下,输出应该是单行中的 A 和“02 01”,第二行中的 B 和“04 26”,如下所示。我该如何解决这种情况。

【问题讨论】:

    标签: python python-3.x regex pandas string


    【解决方案1】:

    您的问题在于在空格上分割线的步骤,这里:

    words = row.Value.split(" ")
    

    因为你用空格分割,字符串'02 01'会被分割成两个'0201'
    要解决这个问题,可以使用内置模块shlex

    import shlex
    ...
    #change this:
    #words = row.Value.split(" ")
    #to this:
    words = shlex.split(row.Value, posix = False)
    #(posix = False) to preserve the inner quotes
    

    【讨论】:

      猜你喜欢
      • 2011-03-11
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2012-01-24
      • 2014-04-08
      • 2020-03-06
      • 2011-06-20
      相关资源
      最近更新 更多