英文:
How to import Excel data in pandas as list?
问题
我的Excel工作表中有一些列,其中之一是类似Python列表的列。如果我使用pandas.read_excel导入这个Excel数据,是否可能让pandas在这个阶段或之后识别该列为列表?我之所以这么问是因为我在Excel中有逗号分隔的值,我想在导入Excel文件后使用pandas的explode()。
我尝试用[""]包装Excel单元格,但导入和展开并未按预期工作。有什么指导吗?
谢谢!
英文:
My Excel worksheet has some columns, one of which is Python list-like column. If I import this Excel data using pandas.read_excel, is it possible for pandas to recognize that column as list at this stage or later? I am asking because I have comma-seperated values residing in Excel and I want to use pandas' explode() after importing the Excel file.
I tried to wrap the Excel cells with [""] but the importing and exploding did not work as desired. Any guidance?
Thanks!
data = {
"Name": ["A", "B", "C","D"],
"Product Sold": [["Apple", "Banana"], ["Apple", "Pear"], ["Pear"], ["Berry"]],
"Prices": [[5,6], [5,8], [4], [3]]
}
df = pd.DataFrame(data)
df.explode(['Product Sold', 'Prices'])
答案1
得分: 1
你可以尝试类似这样的方法:
import pandas as pd
data = {
"Name": "Apple,Pear",
}
df = pd.DataFrame(data, index=[1])
for c in df.columns:
if df[c].str.contains(','):
df[c] = df[c].apply(lambda x: str(x).split(','))
print(type(df.Name.iloc[0]))
读取你的Excel文件,然后将其通过上面的for循环处理,它应该会将逗号分隔的单元格转换成列表。
如果有帮助,请告诉我。
英文:
You could try something like this:
import pandas as pd
data = {
"Name": "Apple,Pear",
}
df = pd.DataFrame(data,index=[1])
for c in pdf.columns:
if df[c].str.contains(','):
df[c] = df[c].apply(lambda x : str(x).split(','))
print(type(df.Name.iloc[0]))
Read in your excel file, then pass it through the for loop above and it should make lists out of comma-delimited cells.
Let me know if it helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论