将列表转换为 Python Dataframe 中的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51209933/
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
Convert list to column in Python Dataframe
提问by Giampaolo Levorato
I have a dataframe df which looks like this:
我有一个数据框 df ,它看起来像这样:
CustomerId Age
1 25
2 18
3 45
4 57
5 34
I have a list called "Price" which looks like this:
我有一个名为“价格”的列表,如下所示:
Price = [123,345,1212,11,677]
I want to add that list to the dataframe. Here is my code:
我想将该列表添加到数据框中。这是我的代码:
df['Price'] = Price
It seems to work but when I print the dataframe the field called "Price" contains all the metadata information such as Name, Type... as well as the value of the Price.
它似乎有效,但是当我打印数据框时,名为“价格”的字段包含所有元数据信息,例如名称、类型...以及价格的值。
How can I create a column called "Price" containing only the values of the Price list so that the dataframe looks like:
如何创建一个名为“Price”的列,该列仅包含价格列表的值,以便数据框如下所示:
CustomerId Age Price
1 25 123
2 18 345
3 45 1212
4 57 11
5 34 677
回答by Quickbeam2k1
In my Opinion, the most elegant solution is to use assign
:
在我看来,最优雅的解决方案是使用assign
:
df.assign(Price=Price)
CustomerId Age Price
1 25 123
2 18 345
3 45 1212
4 57 11
5 34 677
note that assign actually returnsa DataFrame. Assign creates a new Column 'Price' (left Price) with the content of the list Price (right Price)
请注意,assign 实际上返回一个 DataFrame。分配创建一个新的列“价格”(左价格),其中包含列表价格(右价格)的内容
回答by Jorge
I copy pasted your example into a dataframe using pandas.read_clipboard and then added the column like this:
我使用 pandas.read_clipboard 将您的示例复制粘贴到数据框中,然后添加如下列:
import pandas as pd
df = pd.read_clipboard()
Price = [123,345,1212,11,677]
df.loc[:,'Price'] = Price
df
Generating this:
生成这个:
CustomerId Age Price
0 1 25 123
1 2 18 345
2 3 45 1212
3 4 57 11
4 5 34 677
回答by hamza tuna
You can add pandas series as column.
您可以将熊猫系列添加为列。
import pandas as pd
df['Price'] = pd.Series(Price)
回答by akshit0106
import pandas as pd
df['Price'] = pd.Series(Price)
if you use this you will not get the error if you have less values in the series than to your dataframe otherwise you will get the error that will tell you have less vales in the list and that can not be appended.
如果您使用它,如果您的系列中的值少于您的数据帧,您将不会收到错误,否则您将收到错误,告诉您列表中的值较少并且无法附加。