Reputation: 137
I have a dataframe DF1, that has 4 distinct one word named columns, and one identifier column, tz:
Tz, Population, Citibike, Residential, Taxi
Initially, I want to create a dictionary preserving the elements index:
for name in len(DF1.columns):
name = {tz:DF1.name[tz] for tz in DF1.index}
But this produces error either of int object not iterable if I put len(SMdata.columns) or that Dataframe has no object name if I remove the len function from the for loop.
I also have another data frame DF2, to which I am trying to add columns from the first dataframe but most importantly using mapping function on it's column "LocationID".
To do this I tried writing this code:
for name in list(DF1.columns):
Key = name
DF2[name] = DF2.LocationID.map(key)
However, I keep running into "TypeError: 'str' object is not callable"
I am confused as to why is this approach not working!
EDIT: Is it possible to create a loop for getting entries from a column, performing math operation on all values, and adding new val into new column. Basically a loop application for this code:
Df["log_column_name"] = np.log[Df[column_name]]
Upvotes: 0
Views: 464
Reputation: 2165
For the first problem on line
for name in len(DF1.columns):
You are trying to have the for loop loop through len(DF1.columns)
, but len() functions in Python return integers. You may have wanted instead to loop through the DF1.columns itself:
for name in DF1.columns:
For the second problem, it's likely that somewhere in your code, you make a call that is similar to this,
str = ../
The error is complaining that str is an object in python that is not callable, so make sure you do not use any variables named 'str' (because str is a special name in Python).
Referenced from the question here
Upvotes: 1
Reputation: 30930
for name in len(DF1.columns):
This only is execute one time because len()
return one value... then you need for name in df.columns
... but is better use DataFrame.to_dict whit DataFrame.transpose. You don't need a for loop. Pandas provided methods to it.
Example:
import pandas as pd
import numpy as np
df=pd.DataFrame()
df['col1']='a b c d e f'.split()
df['col2']=[1,2,3,4,5,6]
df['col3']=[32,21,'h',2,6,10]
print(df)
rows_dict=df.T.to_dict('list')
print(rows_dict)
col1 col2 col3
0 a 1 32
1 b 2 21
2 c 3 h
3 d 4 2
4 e 5 6
5 f 6 10
{0: ['a', 1, 32], 1: ['b', 2, 21], 2: ['c', 3, 'h'], 3: ['d', 4, 2], 4: ['e', 5, 6], 5: ['f', 6, 10]}
Problem 2
for name in list(DF1.columns):
DF2[name] = DF2.LocationID.map(key)
in any case you would be adding df2 data to other df2 columns, but you are never using df1 data ... please provide an example of what you want to do exactly
Upvotes: 1