python 将带有字符串的Pandas数据框单元格转换为列表

svdrlsy4  于 2023-03-21  发布在  Python
关注(0)|答案(2)|浏览(125)

我有以下Pandas数据框:

Index   Type        Value
0       INT         0
1       INT         100
2       ENUM        "val1","val2","val3"
3       HEX         0x0
4       ENUM        "val1","val2"
5       ENUM        1,4,3,8

下面是我想要的ENUM类型Value行的示例输出:

List = ["val1","val2","val3"]

因此当我调用List[0]时,输出为val1
以下是我的尝试:
1.创建一个空列表并将Value单元格追加到列表中。

for index, row in dataframe.iterrows():
     if(row['Type']=='ENUM'):
        List = []
        List.append(row['Value']
        doSomething()
        List.clear() # I need to clear the list for every iteration

在本例中,列表的长度为1,输出如下所示

List = ['"val1","val2","val3"']
bxgwgixi

bxgwgixi1#

将此字符串转换为列表:

for index, row in dataframe.iterrows():
     if(row['Type']=='ENUM'):
        List = row['Value'].replace('"', '').split(',')
        print(List)

输出:

['val1', 'val2', 'val3']
['val1', 'val2']
['1', '4', '3', '8']

Dataframe 中的永久更改:

m = dataframe['Type'] == 'ENUM'
dataframe.loc[m, 'Value'] = (dataframe.loc[m, 'Value']
                                      .str.replace('"', '')
                                      .str.split(','))
print(dataframe)

# Output
   Type               Value
0   INT                   0
1   INT                 100
2  ENUM  [val1, val2, val3]
3   HEX                 0x0
4  ENUM        [val1, val2]
5  ENUM        [1, 4, 3, 8]

现在,您在Value列中有了真实的的列表。

rlcwz9us

rlcwz9us2#

另一种可能的解决方案:

df['Value'].str.split(',')

输出:

0                       [0]
1                     [100]
2    [val1, "val2", "val3"]
3                     [0x0]
4            [val1, "val2"]
5              [1, 4, 3, 8]
Name: Value, dtype: object

相关问题