![](/img/trans.png)
[英]create a new dataframes with rows from another dataframe with specific columns values
[英]Create a new dataframe with dataframe name, number of rows and columns from multiple dataframes using for loop
我有 2 個數據框。 我想從 2 個數據幀中獲取低於新數據幀的信息。
Desired output
dataFrameName no.rows no.cols
df1Name 100 34
df2Name 212 16
我已經嘗試過如下但收到錯誤
def dfFun(*alldfs):
df = pd.DataFrame(columns=[['dataFrameName ','no.rows','no.cols']], index=[0])
for i in alldfs:
df['dataFrameName'] = i
df['no.rows'] = i.shape[0] # getting error here
df['no.cols'] = i.shape[1]
Function 來電
dfFun('df1Name','df2Name')
錯誤
AttributeError: 'str' object has no attribute 'shape'
我已經理解錯誤但無法獲得所需的 output。
您遇到的錯誤與您調用 function 的方式有關。
dfFun('df1Name','df2Name')
此處使用引號意味着輸入兩個字符串,而不是輸入兩個 dataframe 變量。 因此調用時
df['no.rows'] = i.shape[0]
你得到錯誤
AttributeError: 'str' object has no attribute 'shape'
當您試圖獲得不是 dataframe 的字符串的形狀時。
我了解您還想存儲 dataframe 的變量名。 為此,您應該進行以下調整,如 [here by jfs][1] 所示。
但是,我相信如果您有很多變量,這可能會增加不必要的開銷,因為您需要搜索所有變量。 因此,可能有更好的方法來跟蹤 dataframe。
#get variable name
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
def dfFun(*alldfs):
df = pd.DataFrame(columns=[['dataFrameName ','no.rows','no.cols']], index=[0])
for i in alldfs:
df['dataFrameName'] = namestr(i, globals())[0]
df['no.rows'] = i.shape[0] # getting error here
df['no.cols'] = i.shape[1]
調用這個 function 如下
dfFun(df1, df2)
其中, df1
和df2
只是 pandas 數據幀。 [1]: https://stackoverflow.com/a/592891/14517058
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.