【问题标题】:Excel columns data Need to be converted into list of values enclosed in double quotes and then write to json file by excluding starting brackets [duplicate]Excel列数据需要转换为用双引号括起来的值列表,然后通过排除起始括号写入json文件[重复]
【发布时间】:2019-12-04 09:19:17
【问题描述】:

下面是excel文件

col1 col2

1     a,b,c
2     a

我正在将 excel 文件数据读入数据框

df=pd.read_excel(excel_path, sheetname='data')

df

   col1   col2
0     1   a,b,c
0     2   a

dfj=df.to_json(orient="records")

dfj

'[{"col1":1,"col2":"a,b,c"}]'

这里我需要 dfj 输出是这样的

'{"col1":1,"col2":["a","b","c"]}'

谁能帮我写代码。

【问题讨论】:

  • @Codelt AttributeError: 'Series' 对象没有属性 'split'
  • 我已经发布了我的solution

标签: python json pandas list


【解决方案1】:

使用Series.str.split:

df["col2"] = df["col2"].str.split(",")
dfj = df.to_json(orient="records")
print (dfj)
[{"col1":1,"col2":["a","b","c"]}]

如果可能,多列由字符串填充并需要拆分:

cols = df.select_dtypes('object').columns
df[cols] = df[cols].apply(lambda x: x.str.split(","))
dfj = df.to_json(orient="records")

或创建用于拆分的列列表:

cols = ['col2', 'another col', ...]
df[cols] = df[cols].apply(lambda x: x.str.split(","))
dfj = df.to_json(orient="records")

如果需要删除第一个和最后一个[] 使用strip - .str 不是必需的,因为使用纯python:

dfj = df.to_json(orient="records").strip('[]')
print (dfj)
{"col1":1,"col2":["a","b","c"]}

【讨论】:

  • df.to_json(orient="records") Out[44]: '[{"col1":1,"col2":["a","b","c"]} ]'
  • 这里开始我得到 '[ ,这应该替换为 '
  • @DppriyaReddy - 喜欢dfj = df.to_json(orient="records").strip('[]') ?
  • 它的工作很棒。非常感谢:-)
【解决方案2】:

给你

import json
import pandas as pd

# json string
dfjs = '[{"col1":1,"col2":"a,b,c"}]'

# converting json string into json object 
dfj = json.loads(dfjs)[0]

# converting col2 values into list of values 
dfj["col2"] = dfj["col2"].split(",")

# converting json object into dataframe object
df = pd.DataFrame(dfj)

print(df)

输出

  col1 col2
0     1    a
1     1    b
2     1    c

看到它在行动here

【讨论】:

    猜你喜欢
    • 2019-12-03
    • 2021-06-06
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2021-11-21
    • 2014-05-13
    • 2012-11-21
    • 2016-04-14
    相关资源
    最近更新 更多