我有一些要在DataFrame
中整理为Pandas
的数据。我试图将每一行都设为Series
并将其附加到DataFrame
。我找到了一种方法,将Series
附加到空的list
,然后将list
的Series
转换为DataFrame
例如DF = DataFrame([series1,series2],columns=series1.index)
此list
至DataFrame
步骤似乎过分。我在此处检查了一些示例,但是Series
都没有保留Index
中的Series
标签以用作列标签。
我很长的路要走,列是id_names,行是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()
空数据框
已尝试Insert a row to pandas dataframe仍然得到一个空的数据框:/
[我正在尝试让Series成为行,其中Series的索引成为DataFrame的列标签
[也许一种更简单的方法是使用pandas.Series
的pandas.DataFrame
参数将ignore_index=True
添加到DataFrame.append()
中。例子-
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()
不在适当的位置,它返回附加的数据帧,您需要将其分配回原始数据帧才能正常工作。例子-
DataFrame.append()
要保留标签,您可以使用您的解决方案来添加系列名称,并将附加的DataFrame分配回DF = DF.append(SR_row,ignore_index=True)
。例子-
DF
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()
不会在适当位置修改DataFrame。如果要将其重新分配回原始变量,则需要执行DataFrame.append
。
类似的事情可能起作用...
DataFrame.append
这里是我使用它的示例...
df = df.append(...)
尝试使用此命令。请参见下面的示例:
mydf.loc['newindex'] = myseries
stats = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].describe()
stats
Out[32]:
bp_prob ICD9_prob meds_prob regex_prob
count 171.000000 171.000000 171.000000 171.000000
mean 0.179946 0.059071 0.067020 0.126812
std 0.271546 0.142681 0.152560 0.207014
min 0.000000 0.000000 0.000000 0.000000
25% 0.000000 0.000000 0.000000 0.000000
50% 0.000000 0.000000 0.000000 0.013116
75% 0.309019 0.065248 0.066667 0.192954
max 1.000000 1.000000 1.000000 1.000000
medians = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].median()
stats.loc['median'] = medians
stats
Out[36]:
bp_prob ICD9_prob meds_prob regex_prob
count 171.000000 171.000000 171.000000 171.000000
mean 0.179946 0.059071 0.067020 0.126812
std 0.271546 0.142681 0.152560 0.207014
min 0.000000 0.000000 0.000000 0.000000
25% 0.000000 0.000000 0.000000 0.000000
50% 0.000000 0.000000 0.000000 0.013116
75% 0.309019 0.065248 0.066667 0.192954
max 1.000000 1.000000 1.000000 1.000000
median 0.000000 0.000000 0.000000 0.013116
将系列转换为数据框并转置它,然后正常添加。
df.loc[len(df)] = ['Product 9',99,9.99,8.88,1.11]
df