Python 将列表转换为 Pandas 数据框列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42049147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:10:20  来源:igfitidea点击:

Convert List to Pandas Dataframe Column

pythonlistpandasdataframe

提问by Inherited Geek

I need to Convert my list into a one column pandas dataframe

我需要将我的列表转换为一列熊猫数据框

Current List (len=3):

当前列表(len=3):

['Thanks You',
 'Its fine no problem',
 'Are you sure']

Required Pandas DF (shape =3,):

所需的 Pandas DF(形状 =3,):

0 Thank You
1 Its fine no problem
2 Are you sure

Please note the numbers represent index in Required Pandas DF above.

请注意数字代表上面必需的 Pandas DF 中的索引。

回答by jezrael

Use:

用:

L = ['Thanks You', 'Its fine no problem', 'Are you sure']

#create new df 
df = pd.DataFrame({'col':L})
print (df)

                   col
0           Thanks You
1  Its fine no problem
2         Are you sure


df = pd.DataFrame({'oldcol':[1,2,3]})

#add column to existing df 
df['col'] = L
print (df)
   oldcol                  col
0       1           Thanks You
1       2  Its fine no problem
2       3         Are you sure

Thank you DYZ:

谢谢DYZ:

#default column name 0
df = pd.DataFrame(L)
print (df)
                     0
0           Thanks You
1  Its fine no problem
2         Are you sure

回答by Grant Shannon

if your list looks like this: [1,2,3] you can do:

如果您的列表如下所示:[1,2,3] 您可以:

lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df

to get this:

得到这个:

    col1    col2    col3
0   1       2       3

alternatively you can create a column as follows:

或者,您可以按如下方式创建列:

import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df

to get this:

得到这个:

  col1
0   1
1   2
2   3