![](/img/trans.png)
[英]How to use specific conditions in dataFrame.loc in pandas python?
[英]insert a data into a specific locations in dataframe with dataframe.loc in pandas python
我嘗試使用兩個選項將數據插入 dataframe 中的特定位置。 Option 1 uses fixed colum label and variable index label and Option 2 uses fixed index label and variable colum label and then Option 1 has no error but Option 2 has warning PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`
PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`
選項 1:無警告
import pandas as pd
df=pd.DataFrame()
for col in range(200):
df.loc[str(col),'A']=str(col)
選項 2:警告
df1=pd.DataFrame()
for col in range(200):
df1.loc['A',str(col)]=str(col)
Pandas 實際上並不是為了在循環中重復添加/插入數據而設計的。 這會產生許多昂貴的中間體。
而是使用低級別的 object(列表/字典)循環,最后構造 DataFrame一次。
第一個代碼:
df = pd.DataFrame({'A': {str(i):i for i in range(200)}})
第二個代碼:
df = pd.DataFrame.from_dict({'A': {str(i):i for i in range(200)}}, orient='index')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.