是否可以在不首先创建列表的情况下将Series添加到DataFrame的行? [英] Is it possible to append Series to rows of DataFrame without making a list first?
问题描述
我有一些数据要整理成Pandas
中的DataFrame
.我试图将每一行都设为Series
并将其附加到DataFrame
.我找到了一种方法,将Series
附加到空的list
上,然后将Series
的list
转换为DataFrame
I have some data I'm trying to organize into a DataFrame
in Pandas
. I was trying to make each row a Series
and append it to the DataFrame
. I found a way to do it by appending the Series
to an empty list
and then converting the list
of Series
to a DataFrame
例如DF = DataFrame([series1,series2],columns=series1.index)
此list
至DataFrame
步骤似乎过多.我在这里检查了一些示例,但是Series
都没有保留Series
中的Index
标签以用作列标签.
This list
to DataFrame
step seems to be excessive. I've checked out a few examples on here but none of the Series
preserved the Index
labels from the Series
to use them as column labels.
我很长的路要走,列是id_names,行是type_names:
My long way where columns are id_names and rows are type_names:
是否可以在不首先创建列表的情况下将Series添加到DataFrame的行?
#!/usr/bin/python
DF = DataFrame()
for sample,data in D_sample_data.items():
SR_row = pd.Series(data.D_key_value)
DF.append(SR_row)
DF.head()
TypeError: Can only append a Series if ignore_index=True or if the Series has a name
然后我尝试了
DF = DataFrame()
for sample,data in D_sample_data.items():
SR_row = pd.Series(data.D_key_value,name=sample)
DF.append(SR_row)
DF.head()
空DataFrame
Empty DataFrame
尝试将行插入熊猫数据框 仍然得到一个空的数据框:/
Tried Insert a row to pandas dataframe Still getting an empty dataframe :/
我正在尝试让Series成为行,其中Series的索引成为DataFrame的列标签
推荐答案
也许更简单的方法是将pandas.Series
添加到pandas.DataFrame
中,并且将ignore_index=True
参数设置为DataFrame.append()
.示例-
Maybe an easier way would be to add the pandas.Series
into the pandas.DataFrame
with ignore_index=True
argument to DataFrame.append()
. Example -
DF = DataFrame()
for sample,data in D_sample_data.items():
SR_row = pd.Series(data.D_key_value)
DF = DF.append(SR_row,ignore_index=True)
演示-
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])
In [3]: df
Out[3]:
A B
0 1 2
1 3 4
In [5]: s = pd.Series([5,6],index=['A','B'])
In [6]: s
Out[6]:
A 5
B 6
dtype: int64
In [36]: df.append(s,ignore_index=True)
Out[36]:
A B
0 1 2
1 3 4
2 5 6
代码中的另一个问题是 DataFrame.append()
是如果不是原地,它将返回附加的数据帧,您需要将其分配回原始数据帧才能正常工作.示例-
Another issue in your code is that DataFrame.append()
is not in-place, it returns the appended dataframe, you would need to assign it back to your original dataframe for it to work. Example -
DF = DF.append(SR_row,ignore_index=True)
要保留标签,您可以使用解决方案为系列添加名称,并将附加的DataFrame分配回DF
.示例-
To preserve the labels, you can use your solution to include name for the series along with assigning the appended DataFrame back to DF
. Example -
DF = DataFrame()
for sample,data in D_sample_data.items():
SR_row = pd.Series(data.D_key_value,name=sample)
DF = DF.append(SR_row)
DF.head()
这篇关于是否可以在不首先创建列表的情况下将Series添加到DataFrame的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!