就是这样,我需要将其他数据框中的一行放到pandas中主数据框的顶部,第一行是名为的列。
示例:
1value 2value 3value 4value 5value
acity 4 3 6 2 6
bcity 2 6 6 4 1
ccity 5 11 53 6 3
dcity 5 1 4 6 3
gcity 6 4 2 7 4
另一个样本:
1value 2value 3value 4value 5value
2 5 2 6 3
现在我需要将第二个样本的值添加到第一个样本的顶部。期望的输出:
2 5 2 6 3
1value 2value 3value 4value 5value
acity 4 3 6 2 6
bcity 2 6 6 4 1
ccity 5 11 53 6 3
dcity 5 1 4 6 3
gcity 6 4 2 7 4
仅举此提及,此示例数据框中有大约3000行和250列。
我尝试使用multiindex,但没有用,它说:TypeError: unhashable type: 'dict'
TypeErrorTraceback
(most recent call last)
<ipython-input-230-e17cd26b6b7f> in <module>()
----> 1 pd.MultiIndex.from_arrays([newdf.columns.to_series().map(topframe.iloc[0].to_dict()), newdf.columns])
/opt/anaconda2/lib/python2.7/site-packages/pandas/indexes/multi.pyc in from_arrays(cls, arrays, sortorder, names)
841 return Index(arrays[0], name=name)
842
--> 843 cats = [Categorical.from_array(arr, ordered=True) for arr in arrays]
844 levels = [c.categories for c in cats]
845 labels = [c.codes for c in cats]
/opt/anaconda2/lib/python2.7/site-packages/pandas/core/categorical.pyc in from_array(cls, data, **kwargs)
385 the unique values of `data`.
386 """
--> 387 return Categorical(data, **kwargs)
388
389 @classmethod
/opt/anaconda2/lib/python2.7/site-packages/pandas/core/categorical.pyc in __init__(self, values, categories, ordered, name, fastpath, levels)
286 codes, categories = factorize(values, sort=True)
287 except TypeError:
--> 288 codes, categories = factorize(values, sort=False)
289 if ordered:
290 # raise, as we don't have a sortable data structure and so
/opt/anaconda2/lib/python2.7/site-packages/pandas/core/algorithms.pyc in factorize(values, sort, order, na_sentinel, size_hint)
183 table = hash_klass(size_hint or len(vals))
184 uniques = vec_klass()
--> 185 labels = table.get_labels(vals, uniques, 0, na_sentinel, True)
186
187 labels = com._ensure_platform_int(labels)
pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_labels (pandas/hashtable.c:14033)()
TypeError: unhashable type 'dict
答案 0 :(得分:1)
您可以使用dict
的第一行df2
创建的print (df2.iloc[0].to_dict())
{'2value': 5, '5value': 3, '1value': 2, '4value': 6, '3value': 2}
print (df1.columns.to_series().map(df2.iloc[0].to_dict()))
1value 2
2value 5
3value 2
4value 6
5value 3
dtype: int64
df1.columns = [df1.columns.to_series().map(df2.iloc[0].to_dict()), df1.columns]
print (df1)
2 5 2 6 3
1value 2value 3value 4value 5value
acity 4 3 6 2 6
bcity 2 6 6 4 1
ccity 5 11 53 6 3
dcity 5 1 4 6 3
gcity 6 4 2 7 4
map
来使用iloc
:
rename
另一个解决方案是dict
列print (df1.rename(columns=df2.iloc[0].to_dict()))
2 5 2 6 3
acity 4 3 6 2 6
bcity 2 6 6 4 1
ccity 5 11 53 6 3
dcity 5 1 4 6 3
gcity 6 4 2 7 4
df1.columns = [df1.rename(columns=df2.iloc[0].to_dict()).columns, df1.columns]
print (df1)
2 5 2 6 3
1value 2value 3value 4value 5value
acity 4 3 6 2 6
bcity 2 6 6 4 1
ccity 5 11 53 6 3
dcity 5 1 4 6 3
gcity 6 4 2 7 4
:
Ex:
foreach($api->response as $apiData) {
// Your code
}
答案 1 :(得分:1)
方法如下:
df.iloc[0]=df.iloc[0]+df1.iloc[0